【问题标题】:Angular4 using a collection of objectAngular4使用对象集合
【发布时间】:2017-12-31 13:22:28
【问题描述】:

我正在使用 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);

【问题讨论】:

标签: angular


【解决方案1】:

您好,仅用作 any 的数组,我建议您在 https://www.typescriptlang.org/docs/handbook/basic-types.html 的官方网站中检查文档,这是使用您的示例进行的测试 http://embed.plnkr.co/vsQWITwK48beVWVCiiAI/

【讨论】:

  • 您好,感谢您的解决方案,如果我触发它,它可以正常工作,但如果我使用 Angular CLI(ng new prj-collection)创建一个角度项目并复制/粘贴您的代码。这是错误消息的第一行: ERROR in M:/angular4/prj-collection/src/app/app.component.ts (9,31): Type '{ id: number;名称:字符串; }[]' 不能分配给类型 'any[][]'。键入'{ id:数字;名称:字符串; }' 不可分配给类型 'any[]'。对象字面量只能指定已知属性,并且 'id' 不存在于类型 'any[]' 中......它错过了一个引用,但是哪个?
  • 嗨 @NicolasAlain 只需从 Array 中删除 [],就像这样“ personnes: Array=[{id:1, nom: "Alain"},{id: 2, nom : "Clémentine"},{id: 3, nom: "Cathy"}]; "
  • 太棒了!你是最棒的 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多