【问题标题】:Array ngFor data missing / disappearing数组 ngFor 数据丢失/消失
【发布时间】:2019-01-28 17:41:31
【问题描述】:

我有以下 angular 6 组件来使用 html 表添加新用户:

用户添加.component.html

[...]
<tbody>
    <tr *ngFor="let value of data.pos; let i = index">
        <td><input matInput [(ngModel)]="value.username" name="pos-{{i}}-username"></td>
        <td><input matInput [(ngModel)]="value.firstname" name="pos-{{i}}-firstname"></td>
        <td><input matInput [(ngModel)]="value.lastname" name="pos-{{i}}-lastname"></td>
    </tr>
</tbody>
[...]

user-add.component.ts

export class UserAddComponent {

    data: any = {
        pos: [{modell: '', user: '', asset: '', serial: ''}]
    };

    addPosition(){
        this.data.pos.push({modell: 'c', user: '', asset: '', serial: ''});
        console.log(this.data);
    }

    removePosition(pos){
        this.data.pos.splice([pos],1);
        console.log(this.data);
    }

当我单击一个调用addPosition() 按钮并填写所有输入字段的按钮时,它可以正常工作。

问题:当我单击删除按钮调用函数removePosition(1) 以删除第二行时,它应该会消失。但是当我再次单击addPosition 以添加新行时,第 0 行的数据从 html 表中消失了。 addPosition 中的 console.log() 仍然为 pos 0 输出正确的数据,但在第 0 行的输入字段中不可见。

【问题讨论】:

  • this.data.pos.splice([pos],1); 应该是this.data.pos.splice(pos,1);

标签: javascript angular html-table ngfor


【解决方案1】:

这是一个跟踪问题。通过循环对象并对它们的属性使用双向绑定,你会让 Angular 失去理智。

按功能为其提供自定义跟踪,就像这样

<tr *ngFor="let value of data.pos; let i = index; trackBy: value.id">

(ID = 每个对象的唯一标识符)

或者像这样

<tr *ngFor="let value of data.pos; let i = index; trackBy: customTB">
customTB(index, item) {
  return `${index}-${item.id}`;
}

(你可以返回你想要的,只要它是独一无二的)

【讨论】:

  • 第二个选项效果很好 - 非常感谢
【解决方案2】:

您正在测试哪个浏览器?因为我测试了你的代码,并没有意识到你指定的症状。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多