Push class objects in class array in angular/typescript

Viewed 2942

i have an Agent class

export class Agent{
    ID:number;
    Name: string;
}

And in component i have a variable of this class array

public agents : Agent[];

Now how can i push values in this variable? I have tried following methods but no one worked.

agents.push({"ID":1,"Name":"Abc"});
agents.push(new Agent(){"ID":1,"Name":"Abc"});
4 Answers
agents.push(<Agent>{ ID:1, Name:"Abc" });

or

const _agent = new Agent();
_agent.ID = 1;
_agent.Name = "ABC";

agents.push(_agent);

You need to initialize your array, otherwise you'll get a "cannot read property 'push' of undefined" error. Using a plain object like you did is fine (it's good practice to remove the quotes around the props), e.g.

let agents : Agent[] = [];
agents.push({ ID: 1, Name: "Abc"});
console.log(agents); // outputs: [ { ID: 1, Name: 'Abc' } ]

If you actually want to create an instance of the class, you can do it like this:

const agent = new Agent();
agent.ID = 1;
agent.Name = "ABC";
agents.push(agent);

I think, merely change:

public agents : Agent[]; to public agents : Agent[]= []

and (if you still in the same component and inside a method) :

agents.push({"ID":1,"Name":"Abc"}); to this.agents.push({"ID":1,"Name":"Abc"});


Update:

If you're within the same method:

someMethod(){
  let localAgents :Agent[]= []; 
  localAgents.push({ID:1,Name:"Abc"});
}

If you want to push while declaring, that cannot be done, you merely initialize with default data, why would you push ?

E.g.

  public agents : Agent[] = [{ID:1,Name:"Abc"}];

DEMO

First, your class needs a constructor in order to initialize it with params

export class Agent {
    ID: number;
    Name: string;

    constructor(id: number, name: string) {
        this.ID = id;
        this.Name = name;
    }
}

Then, in your component

...
public agents : Agent[];
...
pushAgent(id: number, name: string) {
    this.agents = [new Agent(id, name)]
}
  • Keep in mind, if you want Angular to display the content of the agents, you must change the array by reference. Otherwise angular would not detect the changes.

Hope this helps!

Related