checkbox true false angular code example
Example 1: data binding on checkbox angular
<input #saveUserNameCheckBox
id="saveUserNameCheckBox"
type="checkbox"
[checked]="saveUsername"
(change)="onSaveUsernameChanged(saveUserNameCheckBox.checked)" />
public saveUsername:boolean;
public onSaveUsernameChanged(value:boolean){
this.saveUsername = value;
}
Example 2: checkbox to select all checkbox angular
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Angular 7 CheckBox Select/ Unselect All';
masterSelected:boolean;
checklist:any;
checkedList:any;
constructor(){
this.masterSelected = false;
this.checklist = [
{id:1,value:'Elenor Anderson',isSelected:false},
{id:2,value:'Caden Kunze',isSelected:true},
{id:3,value:'Ms. Hortense Zulauf',isSelected:true},
{id:4,value:'Grady Reichert',isSelected:false},
{id:5,value:'Dejon Olson',isSelected:false},
{id:6,value:'Jamir Pfannerstill',isSelected:false},
{id:7,value:'Aracely Renner DVM',isSelected:false},
{id:8,value:'Genoveva Luettgen',isSelected:false}
];
this.getCheckedItemList();
}
checkUncheckAll() {
for (var i = 0; i < this.checklist.length; i++) {
this.checklist[i].isSelected = this.masterSelected;
}
this.getCheckedItemList();
}
isAllSelected() {
this.masterSelected = this.checklist.every(function(item:any) {
return item.isSelected == true;
})
this.getCheckedItemList();
}
getCheckedItemList(){
this.checkedList = [];
for (var i = 0; i < this.checklist.length; i++) {
if(this.checklist[i].isSelected)
this.checkedList.push(this.checklist[i]);
}
this.checkedList = JSON.stringify(this.checkedList);
}
}
Copy
Example 3: checkbox to select all checkbox angular
<div style="text-align:center">
<h1>
{{ title }}!
</h1>
</div>
<div class="container">
<div class="text-center mt-5">
<div class="row">
<div class="col-md-6">
<ul class="list-group">
<li class="list-group-item">
<input type="checkbox" [(ngModel)]="masterSelected" name="list_name" value="m1" (change)="checkUncheckAll()"/> <strong>Select/ Unselect All</strong>
</li>
</ul>
<ul class="list-group">
<li class="list-group-item" *ngFor="let item of checklist">
<input type="checkbox" [(ngModel)]="item.isSelected" name="list_name" value="{{item.id}}" (change)="isAllSelected()"/>
{{item.value}}
</li>
</ul>
</div>
<div class="col-md-6">
<code>{{checkedList}}</code>
</div>
</div>
</div>
</div>Copy