Search code examples
angularangular-ngmodelangular-forms

Angular ngModel checks all checkboxes


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


Solution

  • 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 
       }
    
    }