Add items in array angular 4 Add items in array angular 4 typescript typescript

Add items in array angular 4


Yes there is a way to do it.

First declare a class.

//anyfile.tsexport 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


Your 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;    }}