简体   繁体   中英

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.

<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. Without the ngModel the checkboxes are being checked correctly according to the isAvailable field, but then there's no communication with my component. How could I solve this?

With [checked] isntead of ngModel it works fine, checks only those items that have 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] .

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.

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}" . Now everything works as it should. Thank you all for your answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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