Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular material checkbox surrounding div click

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?

like image 296
f0rt1s Avatar asked Mar 12 '26 16:03

f0rt1s


1 Answers

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>
like image 196
Pranay Rana Avatar answered Mar 15 '26 08:03

Pranay Rana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!