如何从 angular material 复选框中获取值

How to get the value from angular material checkbox

我有一个复选框列表:

    <section *ngFor="let item of list">
      <mat-checkbox [checked]="item.value" (click)="toggle(_checkbox_value_here_)">{{item.key}}</mat-checkbox>
    </section>

我需要将 checkbox 值 (_checkbox_value_here_) 传递给我的函数,你会怎么做?

我可以看到这个相关问题 但真的有办法在不使用 ngModelreactive forms 的情况下实现吗?

使用[checked]&[value]绑定值,在(change)事件中传递参数。我创建了一个示例,请在此处查看 https://stackblitz.com/edit/angular-anyw41?file=app/checkbox-configurable-example.html

$event传递给函数

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (click)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

您可以从事件对象中获取函数值..

toggle(event){
  console.log(event)
}

我想会是event.value(这个不确定。你可以在控制台看到)

您可以使用元素的 checked 属性.

<mat-checkbox #c (click)="toggle(!c.checked)">Check me!</mat-checkbox>
  • 注意它是 !c.checked,因为当您点击它时,它还没有被选中。

Stackblitz Demo

The click event on the checkbox is just the native click event, which doesn't know anything about the checkbox itself. Using the change event or just getting a handle on the MatCheckbox instance directly (e.g. with @ViewChildren) would be the recommended approach.

(c) https://github.com/angular/material2/issues/13156#issuecomment-427193381

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (change)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

实际上,没有 ngModel 也是可能的:)

https://stackblitz.com/edit/angular-anyw41-zxrncz?file=app/checkbox-configurable-example.html

您可以使用Kuncevič提到的方法。要获得您想要使用的确切值

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (click)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

并在打字稿中使用 "event.source" 检索值

toggle(event){
  console.log(event.source.value);
}

我是这样解决的:

HTML:

<mat-checkbox class="chklist" labelPosition="after" (change)="seleccionRubros($event)">

TS:

public seleccionRubros(event: MatCheckboxChange) {

   if (!event.source.checked) {
      this.subRubrosSelec = [];
   }

};

请注意我是如何在 (change) 事件中将 $event 传递给 seleccionRubros() 的,后来确定在单击时,通过阅读 [=15= 来选中或取消选中复选框].

作为澄清,我决定指定 event 的类型,但实际上并不需要。