繁体   English   中英

Angular [(ngModel)] 在检查条件的情况下检查所有复选框

[英]Angular [(ngModel)] checks all checboxes in spite of checked condition

我有一个带有帐户的复选框列表。 当我尝试显示带有各种选中/未选中 boolean 值的列表时, [(ngModel)]全部选中/取消选中它们。

<tr *ngFor="let accountSetup of this.accountSetups">
      <td>
      <input type="checkbox"
      [(ngModel)]="accountSetup.isAvailable"
      name="accountSetup">{{accountSetup.name}}
      </td>
</tr>

我看到这个线程Angular ngModel 检查所有复选框,但它并没有帮助我弄清楚如何在我的特定情况下解决这个问题。 如果没有ngModel ,则根据isAvailable字段正确检查复选框,但是与我的组件没有通信。 我怎么能解决这个问题?

使用[checked]而不是ngModel它可以正常工作,只检查那些isAvailable为 true 的项目。 但是使用[checked]我失去了与我的组件的绑定,所以理论上我需要ngModel但它的工作方式与[checked]不同。

我的组件如下所示:

accountSetups: AccountSetup[] = [];

ngOnInit() {
   this.agreementService.getAgreement(this.agreementId).subscribe(data => {
       this.accountSetups = data.accountSetups;
  }
}

当使用带有 typeof 复选框 angular 的 ngModel 时,内部实现CheckboxControlValueAccessor以将 ngModel 与 dom 连接,因此您不需要选中属性来设置复选框状态。

尝试这个:

<tr *ngFor="let accountSetup of this.accountSetups">
      <td>
      <input type="checkbox"
      [(ngModel)]="accountSetup.isAvailable"
      name="accountSetup">{{accountSetup.name}}
      </td>
</tr>

所以我找到了一个解决方案,尽管 boolean 值不同,但它选中/取消选中所有复选框的原因是它缺少[ngModelOptions]="{standalone: true}" 现在一切正常。 谢谢大家的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM