如何在angular 4中使用ngModel绑定数组? [英] How properly bind an array with ngModel in angular 4?

查看:621
本文介绍了如何在angular 4中使用ngModel绑定数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一个数组[1,2,3].我想迭代所有项目并将每个项目绑定到ngModel.当我在更改第一个元素后运行此代码时,第二个元素将获得相同的值.有什么问题吗?

Let's suppose I have an array [1,2,3]. I want to iterate all items and bind each to ngModel. When I run this code after changing the first element, the second one is getting the same value. What's the problem?

<div *ngFor="let x of array; let i = index;">
    <input type="number" [(ngModel)]="x[i]">
</div>

推荐答案

ngFor默认情况下使用对象标识来比较值,这在使用原始值(数字,字符串,布尔值)时会中断,因为修改后它们会更改标识).使用trackBy允许将ngFor配置为zse索引而不是标识:

ngFor by default uses object identity to compare values, this breaks when primitive values (number, string, boolean) are used, because they change identity when modified). Using trackBy allows to configure ngFor to zse the index instead of identity:

<div *ngFor="let x of array; let i = index;trackBy:trackByIdx">
    <input type="number" [(ngModel)]="array[i]">
</div>

trackByIdx(index: number, obj: any): any {
  return index;
}

这篇关于如何在angular 4中使用ngModel绑定数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆