How can I achieve a Material checkbox so It won't get checked/unchecked by default (eg. calling preventDefault()
on the event) and also get the checked
value from the event?
It seems like I can only achieve one of the conditions. Using the (click)
event I cannot get the checkbox's value and using the (change)
event I can't prevent the default checkbox value change (I will only change the checkbox value if the underlying HTTP request was successful).
Stackblitz: https://stackblitz.com/edit/matcheckbox-checked
<mat-checkbox
[checked]="checked"
(click)="onClick($event)"
>onClick me!</mat-checkbox>
<br/>
<mat-checkbox
[checked]="checked"
(change)="onChange($event); false"
>onChange me!</mat-checkbox>
export class CheckboxOverviewExample {
checked: boolean = false;
onClick(event) {
event.preventDefault();
console.log('onClick event.checked ' + event.checked);
console.log('onClick event.target.checked '+event.target.checked);
}
onChange(event) {
// can't event.preventDefault();
console.log('onChange event.checked '+event.checked);
}
}
The (click)
event prints undefined
values, but successfully prevents the event propagation, the (change)
event prints the value but will propagate the event.
Connected issues: