简体   繁体   English

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

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

I have a list of checkboxes with accounts.我有一个带有帐户的复选框列表。 When I try to display the list with various checked/unchecked boolean values [(ngModel)] checks/unchecks them all.当我尝试显示带有各种选中/未选中 boolean 值的列表时, [(ngModel)]全部选中/取消选中它们。

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

I saw this thread Angular ngModel checks all checkboxes but it didn't help me figuring out how to solve this issue in my particular case.我看到这个线程Angular ngModel 检查所有复选框,但它并没有帮助我弄清楚如何在我的特定情况下解决这个问题。 Without the ngModel the checkboxes are being checked correctly according to the isAvailable field, but then there's no communication with my component.如果没有ngModel ,则根据isAvailable字段正确检查复选框,但是与我的组件没有通信。 How could I solve this?我怎么能解决这个问题?

With [checked] isntead of ngModel it works fine, checks only those items that have isAvailable true.使用[checked]而不是ngModel它可以正常工作,只检查那些isAvailable为 true 的项目。 But with [checked] I lose binding with my component, so in theory I need ngModel but it doesn't work the same way as [checked] .但是使用[checked]我失去了与我的组件的绑定,所以理论上我需要ngModel但它的工作方式与[checked]不同。

My component looks like this:我的组件如下所示:

accountSetups: AccountSetup[] = [];

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

When using ngModel with typeof checkbox angular internally implement CheckboxControlValueAccessor to connect ngModel with dom and so you don't need checked attribute to set checkbox status.当使用带有 typeof 复选框 angular 的 ngModel 时,内部实现CheckboxControlValueAccessor以将 ngModel 与 dom 连接,因此您不需要选中属性来设置复选框状态。

Try this:尝试这个:

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

So I've found a solution, the reason it checked/unchecked all of the checkboxes in spite of different boolean values was because it lacked [ngModelOptions]="{standalone: true}" .所以我找到了一个解决方案,尽管 boolean 值不同,但它选中/取消选中所有复选框的原因是它缺少[ngModelOptions]="{standalone: true}" Now everything works as it should.现在一切正常。 Thank you all for your answers.谢谢大家的答案。

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

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