How to implement select all in mat-checkbox angular 5
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.
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>
- 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>
unSelectAll() {
this.emp.forEach(element => {
element.checked = false;
});
}
Solution 2
I think @Arash suggestion is very good.
Just update his function "selectAll" to also be able to deselect as well:
this.emp.forEach(element => {
element.checked = element.checked ? false : true;
});
Another option would be to check what value the "select all" checkbox has:
public selectAll() {
var value = this.checked ? false : true;
this.emp.forEach(element => {
element.checked = value;
});
}
mjck
I am a front end developer, working in web development since 8 years, initially i started with PHP development, now full time working on front end.
Updated on June 14, 2022Comments
-
mjck about 2 years
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.
-
mjck about 6 yearsThank you for the response, is there any way to deselect all, when unchecked the select all check box.
-
Arash about 6 yearsI will update my post , please mark the answer if it helps :)
-
mjck about 6 yearsits working almost fine, thanks again, only issue I am facing, if I click on unselect all, select all button still showing selected.
-
Arash about 6 yearsadd this.checked = false; into unSelectAll() function.
-
mr3k about 4 yearsHi @Arash! I would suggest to update your function "selectAll" with the following content to make it possible to select all and deselect all on the checkbox:
this.emp.forEach(element => { element.checked = element.checked ? false : true; });