简体   繁体   中英

“Deselect all checkboxes” not working with angular property binding

I have used property binding in angular to deselect all checkboxes, but it is not working as expected. What i expected: After selecting one or more checkboxes when i click 'clear' button it should deselect all checkboxes. here is my plunker

isSelected is the boolean variable which i have used to set the 'checked' attribute of checkbox. 

template:

<div *ngFor="let item of items">
    <input [checked]="isSelected" type="checkbox">{{item}}
</div>
<button (click)="onClear()">Clear All</button>

Component

private items = ['a', 'b', 'c', 'd'];
  private isSelected = false;
  constructor() {
  }

  onClear(){
    this.isSelected = false;
  }

Set ngModel on your checkboxes and track the changes with ngModelChange . Also Set an auxiliary array to help you track the checked status. Here is a (simplified) example:

HTML

<input [ngModel]="isSelected[i]" (ngModelChange)="onChange(i)" type="checkbox">{{item}}

Typescript

 isSelected =  [];
 constructor() {
   this.onClear();
 }

 onChange(i){
    this.isSelected[i]=!this.isSelected[i]
  }
  onClear(){
    this.isSelected = [false, false, false, false];
  }

DEMO

One solution is

<div *ngFor="let item of items">
    <input [(ngModel)]="item.checked" type="checkbox">{{item.label}}
</div>
<button (click)="onClear()">Clear All</button>

with the template:

private items = [ {'label':'a', 'checked': false },
  {'label':'b', 'checked': false},
  {'label':'c', 'checked': false},
  {'label':'d', 'checked': false}];

onClear(){
    for ( let cb of this.items ) {
      cb.checked = false;
    }
  } 

At first, you should know [checked] not working and you should use [(ngModel)] for this thing and you should import FormModule from @angular/forms.

second, you should have multiple isSelected variable because if you use just one isSelected variable when you select one of them, all checkboxes will be select, for that you can use array like this in .ts file,

items = [{name: 'a', isSelected:false}, 
         {name: 'b', isSelected:false},
         {name: 'c', isSelected:false},
         {name: 'd', isSelected:false}];

and in HTML

<div *ngFor="let item of items">
    <input [(ngModel)]="item.isSelected" type="checkbox">{{item.name}}
</div>

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