【问题标题】:Checkboxes generated with ngFor array not updating when array changes使用 ngFor 数组生成的复选框在数组更改时不会更新
【发布时间】:2019-01-11 17:59:09
【问题描述】:

我有一个需要用复选框表示的项目数组(itemsarray)。我有另一个数组(addItem),其中包含已检查的项目。

每当 addItem 由于用户选择而在后台更改时,复选框不会更新。此外,如果从 addItem 中手动删除元素,则复选框不会更新。

<div class="form-group">
   <label class="control-label col-sm-12" for="secname">Choose Your Items</label>
   <div class="col-sm-10" *ngFor="let item of itemsarray; let i=index">
       <input type="checkbox" [checked]='additem.indexOf(item)>-1' (click)='checkditem($event,item)' >{{item.itemname.itemname}}
   </div>
</div>

【问题讨论】:

标签: angular checkbox


【解决方案1】:

我相信 addItem.indexOf(item) 在比较引用时会返回 -1。

尝试创建一个函数来检查(通过属性) addItem 数组是否包含项目对象。

例如。

itemChecked(item)
{
    const res = addItem.find(i => i.id === item.id);
     return res !== undefined;
}

在你看来:

<input type="checkbox" [checked]='itemChecked(item)' (click)='checkditem($event,item)'>{{item.itemname.itemname}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2018-08-09
    • 2018-06-17
    • 2019-01-26
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多