html - Angular5 在用 ngfor 显示它的同时在数组中插入元素

标签 html angular typescript angular5

我有一个对象数组 (config.lensTab),我在我的 Html 中用 ngFor 显示这些对象:

<tr *ngFor="let item of config.lensTab; let i = index;">
          <th scope="row">{{ i + 1}}</th>
          <th><label></label>
          <input [(ngModel)]="item.radius" class="form-control"
                             type="number" step="0.01" name="radius-{{i}}</th>
[...]

我添加了一个“+”按钮,它会在我的数组中的给定索引 (idx) 中插入一个元素:

  public addLens(idx: number) {
           let toAdd = new LensModel(0, 0, 0,
           new MaterialModel('Air', 0), 0, 0);
           this.config.lensTab.splice(idx + 1, 0, toAdd);
     }

当我用 console.log 显示数组的内容时,插入操作似乎正常工作。但是在我的 html View 中,新行旁边的行与该新行具有相同的值。

我给你一个简单的例子来理解:

Tab : [RED, GREEN, WHITE] --> add "BLUE" at index 1 ---> [RED, BLUE, BLUE, WHITE]

我做错了什么?

编辑:这就是我初始化配置对象的方式

this.config = new ConfigModel();
this.config.lensTab = [];

this.config.lensTab.push(new LensModel(1, 2, 3, new MaterialModel('Acier', 12), 4, 5));

编辑2:

Before clicking the "+" button

after clicking the "+" button

笨蛋:https://embed.plnkr.co/DghlRr/

最佳答案

我使用了 Angular trackBy 函数,以便 ngFor 检测到变化。

https://plnkr.co/edit/iyXOgVSwN2VuJT64YxrT?p=preview

<div *ngFor="let item of config.lensTab; let i = index; trackBy: trackByFn">

    trackByFn(index, item) {
return index;  }

已更新 plunker。

关于html - Angular5 在用 ngfor 显示它的同时在数组中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49938750/

相关文章:

html - 在 html 列中换行

javascript - "html?v=<%= VERSION %>"是什么意思?

javascript - TypeScript:在没有显式返回类型的情况下,不会在 lambda 中检查多余的属性

angular - 与安全导航运营商的双向绑定(bind)

typescript - 使用 Vue 3 + vue-class-component + TypeScript 的 Vuelidate

typescript 折线图 d3

javascript - 绕过 stopPropagation()

html - CSS 给表格添加边框

javascript - 输入后替换url的最后5个字符

angular - 转换枚举结构值:key to key:value in TypeScript