Reputation: 2902
I want to check is checkbox is checked or unchecked in an if and else statement.
<md-checkbox id="mon" (change)="mon($event)" [checked]="true">Checked</md-checkbox>
mon(e){
if(e.target.checked){
console.log("This is checked")
} else {
console.log("unchecked");
}
}
I think I am doing it really wrong. I keep getting can't get checked of undefined. How is the way to do this?
Upvotes: 4
Views: 23574
Reputation: 6147
declare a variable called it filter
filter: boolean= false;
then use ngModel in html part to access and assign its value.
<input type="checkbox" [(ngModel)]="filter" (click)="filterData()">
it will call a function filterData() which you can use to do all your functionality
filter(){
this.filter = !this.filter;// this will change value of it true and false
}
for more checkbox you can use declare more variable like filter1: boolean
Upvotes: 6
Reputation: 214295
We can look at source code of material checkbox:
event.source = this;
event.checked = this.checked;
this._controlValueAccessorChangeFn(this.checked);
this.change.emit(event);
https://github.com/angular/material2/blob/2.0.0-alpha.11/src/lib/checkbox/checkbox.ts#L288-L292
So you can do it like:
mon(e){
if(e.checked){
console.log("This is checked")
} else {
console.log("unchecked");
}
}
Upvotes: 5