Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"});
like image 248
Hunzla Ali Avatar asked Sep 14 '25 03:09

Hunzla Ali


2 Answers

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

like image 138
SeleM Avatar answered Sep 15 '25 18:09

SeleM


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

or

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

agents.push(_agent);
like image 28
aelagawy Avatar answered Sep 15 '25 16:09

aelagawy