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
The arr. push() method is used to push one or more values into the array, & new values will add at the end of an array. This method changes the length of the array by the number of elements added to the array & returns the new length of the modified array.
The push() method is a built-in method in AngularJS that inserts an object into an existing array. It takes two arguments: the object to push and the index of the position to insert the object. The first argument is the object that will be pushed into the array and should be of type string, number, boolean, or null.
The push() function is a built-in array method of JavaScript. It is used to add the objects or elements in the array. This method adds the elements at the end of the array. "Note that any number of elements can be added using the push() method in an array."
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 - https://www.typescriptlang.org/docs/handbook/interfaces.html
Also checkout this question, it is very interesting - When to use Interface and Model in TypeScript / Angular2
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