Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncheck all check boxes created with *ngFor

Tags:

angular

I have a table which has a column that contains a checkbox for each row using *ngFor. Upon clicking a button I want to uncheck all the checkboxes. I tried using [(ngModel)]="boxChecked" for each checkbox and setting that value to false in the method that my button click calls but that results in each checkbox being checked whenever I check only one of them. This does uncheck all checkboxes upon button click but I still need to be able to individually check the checkboxes.

<ng-template pTemplate="body" let-sub let-expanded="expanded" let-columns="columns">
      <tr [pSelectableRow]="subcontract">
        <td *ngFor="let col of columns" [ngSwitch]="true" style="text-align: center">
          <div *ngSwitchCase="col.export" ><input type="checkbox" (change)="checked($event, sub)" [(ngModel)]="boxChecked"></div>
        </td>
      </tr>
</ng-template>
<button type="button"(click)="reset(table)"></button>

ts:

//I send the ID of the table to this method.
reset(table) {
    table.reset();
    this.boxChecked = false;
}

So far in my research I don't see that there is a get(index i)(to get a single row of the index parameter) method of some sort on my table. Then I could easily just loop through my table and set the checkbox of each iteration(row) to false.

like image 218
Drew13 Avatar asked Aug 07 '18 13:08

Drew13


1 Answers

Since the check boxes are not bound to a property (which could be reset to uncheck the box), you can use a template reference variable (e.g. #checkboxes):

<input #checkboxes type="checkbox" ...>
...
<button type="button" (click)="uncheckAll()"></button>

to retrieve the check boxes with ViewChildren in the code and uncheck each one:

@ViewChildren("checkboxes") checkboxes: QueryList<ElementRef>;

uncheckAll() {
  this.checkboxes.forEach((element) => {
    element.nativeElement.checked = false;
  });
}

See this stackblitz for a demo.

like image 122
ConnorsFan Avatar answered Oct 14 '22 13:10

ConnorsFan