Art*_*ory 5 html typescript angular 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>
[...]
Run Code Online (Sandbox Code Playgroud)
我添加了一个“+”按钮,它将在数组中的给定索引(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);
}
Run Code Online (Sandbox Code Playgroud)
当我用 console.log 显示数组的内容时,插入操作似乎工作正常。然而,在我的 html 视图中,新行旁边的行与该新行具有相同的值。
我给你一个简单的例子来帮助理解:
Tab : [RED, GREEN, WHITE] --> add "BLUE" at index 1 ---> [RED, BLUE, BLUE, WHITE]
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么 ?
编辑:这就是我初始化配置对象的方式
this.config = new ConfigModel();
this.config.lensTab = [];
this.config.lensTab.push(new LensModel(1, 2, 3, new MaterialModel('Acier', 12), 4, 5));
Run Code Online (Sandbox Code Playgroud)
编辑2:
我使用了角度的 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; }
Run Code Online (Sandbox Code Playgroud)
已经更新了plunker。
| 归档时间: |
|
| 查看次数: |
782 次 |
| 最近记录: |