Hunzla Ali
Hunzla Ali

Reputation: 423

Push class objects in class array in angular/typescript

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"});

Upvotes: 4

Views: 4600

Answers (4)

aelagawy
aelagawy

Reputation: 577

agents.push({ ID:1, Name:"Abc" } as Agent);

or

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

agents.push(_agent);

Upvotes: 1

Ben Ari Kutai
Ben Ari Kutai

Reputation: 569

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!

Upvotes: 0

SeleM
SeleM

Reputation: 9648

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

Upvotes: 1

eol
eol

Reputation: 24565

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);

Upvotes: 0

Related Questions