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"});
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
agents.push({ ID:1, Name:"Abc" } as Agent);
or
const _agent = new Agent();
_agent.ID = 1;
_agent.Name = "ABC";
agents.push(_agent);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With