Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
48
rated 0 times [  54] [ 6]  / answers: 1 / hits: 15589  / 6 Years ago, sun, june 10, 2018, 12:00:00

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.


More From » angular

 Answers
30

  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;
});
}

[#54238] Wednesday, June 6, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
neob

Total Points: 253
Total Questions: 106
Total Answers: 104

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;