Is there a way to customize a Material checkbox to prevent it from being checked or unchecked by default (e.g., by calling preventDefault()
on the event) and still retrieve the checked
value from the event?
It appears that achieving both conditions simultaneously is challenging. When using the (click)
event, retrieving the checkbox's value seems impossible, while with the (change)
event, preventing the default checkbox value change becomes tricky (one would prefer to change the checkbox value only after a successful underlying HTTP request).
Find the Stackblitz example here: https://stackblitz.com/edit/matcheckbox-checked
<mat-checkbox
[checked]="checked"
(click)="onClick($event)"
>Click me!</mat-checkbox>
<br/>
<mat-checkbox
[checked]="checked"
(change)="onChange($event); false"
>Change 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) {
// Unable to use event.preventDefault();
console.log('onChange event.checked '+event.checked);
}
}
The (click)
event produces undefined
values but successfully halts event propagation, while the (change)
event retrieves the value but allows event propagation.
Check out related issues here: