I have an angular 5 material checkbox with a surrounding div and some other elements. I want a click on the div to be the same as a click directly on the checkbox.
Here is my example code:
<div (click)="checked = !checked">
<mat-checkbox class="example-margin" [(ngModel)]="checked">
I'm a not working checkbox :'(
</mat-checkbox>
<span style="background-color: #dddd00;">I want to be clickable too</span>
</div>
and a Stackblitz
At the moment clicking on the checkbox itself is not working, clicking outside the div works. Any ideas?
Issue here is event of Click on div and [(ngModel)] on checkbox both nullify each other thats the reason its not working.
To make it work you need to stopPropagation, when you click on div element. so i did code as below returning false from div click event that stop it and you code will work.
Working Demo
component.ts
export class CheckboxConfigurableExample {
checked = false;
indeterminate = false;
align = 'start';
disabled = false;
onChecked() {
this.checked= !this.checked;
return false;
}
}
component.thml
<mat-card class="result">
<mat-card-content>
<h2 class="example-h2">Result</h2>
<section class="example-section">
<div (click)="onChecked();">
<mat-checkbox class="example-margin" [(ngModel)]="checked">
not working checkbox :'(
</mat-checkbox>
<span style="background-color: #dddd00;">I want to be clickable too</span>
</div>
</section>
</mat-card-content>
</mat-card>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With