首页 > 解决方案 > 如果在 ngFor 中使用,如何获取 mat-checkbox 检查值

问题描述

我正在尝试获取所有已检查的复选框并对其执行某些功能。

<div class="outerdiv" *ngFor="let item of items">
<mat-checkbox>Hello</mat-checkbox>
<div>

<button (click)="filterSelectedItems()"></button>

filterSelectedItems(){
let outerdiv = this.element.nativeElement.querySelectorAll('.outerdiv');
 for(let i = 0; i < outerdiv.length; i++){
      let option = outerdiv[i].querySelector('mat-checkbox');
      if(option.checked){
        this.filterItem+=option.innerText;
      }
}

标签: angularangular-material

解决方案


您可以在此StackBlitz Link中获得 Total工作示例

您的 html 是,并且onChange复选框getCheckbox()事件触发。这里我们传递模板引用变量#checkBox

<div *ngFor ="let item of items">
     <mat-checkbox #checkBox [value]="item" (change)="getCheckbox(checkBox)">  
          {{item}} 
     </mat-checkbox>
</div>

<div *ngFor="let checkedItem of checked">
     <span> selected Key is: <strong>   {{checkedItem.value }} </strong> : 
            <strong> {{checkedItem.checked}} </strong> 
     </span>
</div>

您可以使用这样的方式获取文件中#checkBox数组...component.ts@ViewChildren()QueryList

  @ViewChildren ('checkBox' ) checkBox:QueryList<any>;
    checked = [];
    items =['one','two', 'three', 'four'];

  getCheckbox(checkbox){
      this.checked = []; // resetting each Time new event is fire.
   // filtering only checked vlaue and assign to checked variable.
    const checked = this.checkBox.filter(checkbox => checkbox.checked);

   // then, we make object array of checked, and value by checked variable  
      checked.forEach(data => {
           this.checked.push ({
               'checked' : data.checked,
               'value':  data.value
           })
      })
  }

推荐阅读