div单击的角度材料复选框

时间:2018-03-15 13:29:25

标签: angular angular-material2

我有一个angular 5 material checkbox周围的div和其他一些元素。我希望点击divclick上的checkbox直接相同。

这是我的示例代码:

<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>

Stackblitz

目前点击复选框本身不起作用,点击div外部工作。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

此处的问题是Click上的div事件以及[(ngModel)]复选框上的事件均相互抵消,原因是它不起作用。

要使其正常工作,当您单击div元素时,需要stopPropagation。所以我在div点击事件中执行了returning false下面的代码,停止了它,你的代码就可以了。

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>
相关问题