Add items in array angular 4
Mia Lopez
I have following code
export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { }
ngOnInit() { }
onEmpCreate(){ console.log(this.name,this.empoloyeeID); this.empList.push.apply(this.name,this.empoloyeeID); this.name =""; this.empoloyeeID = 0; }
}but this throwing error
CreateListFromArrayLike called on non-object
Also is there any way to create a custom class and used object list rather than defining array over here.
Thanks
3 Answers
Yes there is a way to do it.
First declare a class.
//anyfile.ts
export class Custom
{ name: string, empoloyeeID: number
}Then in your component import the class
import {Custom} from '../path/to/anyfile.ts'
.....
export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<Custom> = []; constructor() { } ngOnInit() { } onEmpCreate(){ //console.log(this.name,this.empoloyeeID); let customObj = new Custom(); customObj.name = "something"; customObj.employeeId = 12; this.empList.push(customObj); this.name =""; this.empoloyeeID = 0; }
}Another way would be to interfaces read the documentation once -
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
3Your empList is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID}); Push object into your array. Try this:
export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() {} ngOnInit() {} onEmpCreate(){ console.log(this.name,this.empoloyeeID); this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID }); this.name = ""; this.empoloyeeID = 0; }
} 0