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.
You should define a boolean property for emp list something like checked now your emp list has a property known check other than name.
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>
<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>
unSelectAll() {
this.emp.forEach(element => {
element.checked = false;
});
}