2017-07-25 123 views
0

我正在使用Angular4,我不知道如何声明对象集合,然后添加项目和删除项目? 感谢您的帮助Angular4使用对象集合

这里是什么做的: 组件:

import { Component } from '@angular/core'; 
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    // tableaux d'objets 
    personnes: Object[]=[{id:1, nom: "Alain"},{id: 2, nom: "Clémentine"},{id: 3, nom: "Cathy"}]; 
} 

模板:

<table> 
    <tr *ngFor="let personne of personnes"> 
     <td>{{personne.id}}</td> 
     <td>{{personne.nom}}</td> 
    </tr> 
</table> 

它工作正常,但现在我想管理我的对象的集合,例如用户将提供数据,我将用这些数据创建一个新对象,然后将这个新对象添加到我的集合中。 我想这一点,但它不工作:

personnes: Object[] = []; 
personne: any = {{id:1, nom: "Alain"}; 
this.personnes.push(this.personne); 

personnes: any[] = []; 
personne: any = {{id:1, nom: "Alain"}; 
this.personnes.push(this.personne); 
+1

https://stackoverflow.com/questions/12870291/typescript-typed-array-usage谷歌是你最好的朋友 –

+0

在什么情况下... http get,* ngFor,other ? – JGFMK

+0

请指定更详细的“对象集合”。对象是什么样的?你想用这个系列做什么? –

回答

0

喜就像任何阵列使用,我会建议检查文档在这个官方网站在https://www.typescriptlang.org/docs/handbook/basic-types.html,这是一个测试使用你的例子http://embed.plnkr.co/vsQWITwK48beVWVCiiAI/

+0

您好,感谢您的解决方案,如果我将它解雇,但工作正常,但如果我使用Anglar CLI(ng new prj-collection)创建一个角度项目,然后复制/粘贴您的代码。这是错误消息的第一行:M:/angular4/prj-collection/src/app/app.component.ts(9,31)中的错误:键入'{id:number; nom:string; } []'不可分配为键入'any [] []'。输入'{id:number; nom:string; }'不可分配为键入'any []'。对象字面量只能指定已知的属性,'id'在类型'any []'中不存在......它错过了一个引用,但是哪个? –

+0

嗨@NicolasAlain只是删除[]阵列,就像“personnes:Array = [{id:1,nom:”Alain“},{id:2,nom:”Clémentine“},{id:3, nom:“Cathy”}];“ –

+0

太棒了!你是最棒的 ;-) –