首页 > 解决方案 > 在 *ngfor 复选框列表中定位一个复选框

问题描述

我有一个绑定到我的组件打字稿文件中的对象的复选框列表,我希望它在用户单击复选框时选中/取消选中列表,但由于某种原因,它只选中并取消选中第一个复选框列表,而不是用户单击的列表。下面是代码:

<div>
  <ul class="reports-container">
    <li *ngFor="let item of data.reports" [class.active]="selectedReport==item" >
      <input type="checkbox" id="{{'savedreport'+i}}" class="k-checkbox" [checked]="item.IsSubscribed" [value]="item.IsSubscribed"(change)="onChkBoxChange($event,item)" />
    </li>
   </ul>
</div>

这是打字稿功能:

onChkBoxChange(event, item: SavedReport) {
   item.IsSubscribed = event.target.checked;
}

当我放一个断点时,它总是在列表中的第一项中传递,有什么想法吗?

标签: htmlangulartypescriptcheckbox

解决方案


正如@Michael Beeson 建议的那样,我在我的复选框值上使用了双向绑定,这解决了问题,所以现在的代码是:

<div>
  <ul class="reports-container">
    <li *ngFor="let item of data.reports" [class.active]="selectedReport==item" >
      <input type="checkbox" id="{{'savedreport'+i}}" class="k-checkbox" [checked]="item.IsSubscribed" [(value)]="item.IsSubscribed"(change)="onChkBoxChange($event,item)" />
    </li>
   </ul>
</div>

推荐阅读