Angular ngModel checks all checkboxes

不打扰是莪最后的温柔 提交于 2021-01-29 09:01:10

问题


Trying to check/uncheck all children checkboxes using ngModel and all checkboxes are checked, but also trying to check alone children and all checkboxes are always checked;

<div>
    <input type="checkbox" [checked]="myVar1" (change)="myVar1 = !myVar1" /> Parent
  </div>
  <ul>
    <input type="checkbox" [(ngModel)]="myVar1" /> Child1<br>
    <input type="checkbox" [(ngModel)]="myVar1" /> Child2
  </ul>

Tried using [ngModelOptions]="{standalone: true}" property and it results with the same behaviour - all checkboxes are checked;

 <div>
    <input type="checkbox" [checked]="myVar2" (change)="myVar2 = !myVar2" /> Parent
  </div>
  <ul>
    <input type="checkbox" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}" /> Child1<br>
    <input type="checkbox" [(ngModel)]="myVar2" [ngModelOptions]="{standalone: true}" /> Child2
  </ul>

How to make every child checkbox standalone? stackblitz


回答1:


You are using the same [(ngModel)] for child and parent which makes the child checked as soon as parent is checked.

You need to have different [(ngModel)] for children and use a checked/changed function on parent checkbox to do the check all child i.e set child ngModel to true or false.

EX:

<div>
    <input type="checkbox" [checked]="myVar1" (change)="updateChildSelection($event)" /> Parent
  </div>
  <ul>
    <input type="checkbox" [(ngModel)]="myVarChild1" /> Child1<br>
    <input type="checkbox" [(ngModel)]="myVarChild2" /> Child2
  </ul>

In component:

updateChildSelection(event) {
  // set child to true if checked
   if(event.target.checked){
    this.myVarChild1 = true;
    this.myVarChild2 = true
   } else {
   //set child model to false 
   }

}


来源:https://stackoverflow.com/questions/56137453/angular-ngmodel-checks-all-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!