在数组 angular 4 中添加项目

新手上路,请多包涵

我有以下代码

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

但是这个抛出错误

CreateListFromArrayLike 在非对象上调用

还有什么方法可以创建自定义类和使用的对象列表,而不是在这里定义数组。

谢谢

原文由 Md. Parvez Alam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 636
2 个回答

是的,有办法做到这一点。

首先声明一个类。

 //anyfile.ts
export class Custom
{
  name: string,
  empoloyeeID: number
}

然后在您的组件中导入该类

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

另一种方法是 接口 阅读文档一次 - https://www.typescriptlang.org/docs/handbook/interfaces.html

还要检查这个问题,这很有趣 -When to use Interface and Model in TypeScript / Angular2

原文由 Srinivas Valekar 发布,翻译遵循 CC BY-SA 3.0 许可协议

将对象推送到您的数组中。尝试这个:

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

原文由 Faly 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进