Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items in array angular 4

Tags:

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

like image 969
Md. Parvez Alam Avatar asked Nov 03 '17 06:11

Md. Parvez Alam


People also ask

How to add array value in angular?

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.

How to add an object in object array angular?

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.

How do you add an object to an array?

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."


1 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 - 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

like image 139
Srinivas Valekar Avatar answered Sep 20 '22 04:09

Srinivas Valekar