1<div style="text-align:center">
2 <h1>
3 {{ title }}!
4 </h1>
5</div>
6<div class="container">
7 <div class="text-center mt-5">
8 <div class="row">
9 <div class="col-md-6">
10 <ul class="list-group">
11 <li class="list-group-item">
12 <input type="checkbox" [(ngModel)]="masterSelected" name="list_name" value="m1" (change)="checkUncheckAll()"/> <strong>Select/ Unselect All</strong>
13 </li>
14 </ul>
15 <ul class="list-group">
16 <li class="list-group-item" *ngFor="let item of checklist">
17 <input type="checkbox" [(ngModel)]="item.isSelected" name="list_name" value="{{item.id}}" (change)="isAllSelected()"/>
18 {{item.value}}
19 </li>
20 </ul>
21 </div>
22 <div class="col-md-6">
23 <code>{{checkedList}}</code>
24 </div>
25 </div>
26 </div>
27</div>Copy
1import { Component } from '@angular/core';
2
3@Component({
4 selector: 'app-root',
5 templateUrl: './app.component.html',
6 styleUrls: ['./app.component.scss']
7})
8export class AppComponent {
9 title = 'Angular 7 CheckBox Select/ Unselect All';
10 masterSelected:boolean;
11 checklist:any;
12 checkedList:any;
13
14 constructor(){
15 this.masterSelected = false;
16 this.checklist = [
17 {id:1,value:'Elenor Anderson',isSelected:false},
18 {id:2,value:'Caden Kunze',isSelected:true},
19 {id:3,value:'Ms. Hortense Zulauf',isSelected:true},
20 {id:4,value:'Grady Reichert',isSelected:false},
21 {id:5,value:'Dejon Olson',isSelected:false},
22 {id:6,value:'Jamir Pfannerstill',isSelected:false},
23 {id:7,value:'Aracely Renner DVM',isSelected:false},
24 {id:8,value:'Genoveva Luettgen',isSelected:false}
25 ];
26 this.getCheckedItemList();
27 }
28
29 checkUncheckAll() {
30 for (var i = 0; i < this.checklist.length; i++) {
31 this.checklist[i].isSelected = this.masterSelected;
32 }
33 this.getCheckedItemList();
34 }
35 isAllSelected() {
36 this.masterSelected = this.checklist.every(function(item:any) {
37 return item.isSelected == true;
38 })
39 this.getCheckedItemList();
40 }
41
42 getCheckedItemList(){
43 this.checkedList = [];
44 for (var i = 0; i < this.checklist.length; i++) {
45 if(this.checklist[i].isSelected)
46 this.checkedList.push(this.checklist[i]);
47 }
48 this.checkedList = JSON.stringify(this.checkedList);
49 }
50
51}
52Copy
1Prepared a small demo to show how this can be done using ngModel directive. Link: https://stackblitz.com/edit/angular-lxjrdh
2
3It uses Array.every to check if all are checked or not. If checked, it resets all otherwise checks all.