javascriptangularangular5angular-material-5

How to implement select all in mat-checkbox angular 5


Here is my html template

<mat-card>
    <mat-card-content>
        <h2 class="example-h2">Select Employee</h2>    
        <section class="example-section">
            <mat-checkbox  [(ngModel)]="checked">Select All</mat-checkbox>
        </section>   
        <section class="example-section" *ngFor="let r of emp">
            <mat-checkbox class="example-margin" [(ngModel)]="checked">{{r.name}}</mat-checkbox>
        </section> 
    </mat-card-content>
</mat-card> 

This is code is not working properly, if I click on select all, its selecting all the check boxes, if I select on individual check box, its also selecting all the items.

Please help.


Solution

    1. You should define a boolean property for emp list something like checked now your emp list has a property known check other than name.

    2. Change ngModel for checkboxes like below

    <section class="example-section" *ngFor="let r of emp">
      <mat-checkbox class="example-margin" [(ngModel)]="r.checked">{{r.name}}</mat-checkbox>  
    </section>

    1. For check all checkboxes you should add a click function to you'r Select All checkbox like below .

    <mat-checkbox  [(ngModel)]="checked" (click)="selectAll()">Select All</mat-checkbox>

    And at the end add selectAll() function to you'r component i.e

      selectAll() {
        this.emp.forEach(element => {
          element.checked = true;
        });
      }
    

    update

    For unselect all checkboxes you can add a button like below

    <button (click)="unSelectAll()">UnSelect all</button>
    and add its function in you'r ts file like below

      unSelectAll() {
        this.emp.forEach(element => {
          element.checked = false;
        });
      }