如何检查angular5中的所有mat-checkbox?

时间:2018-10-30 03:38:05

标签: angular

<form>
<mat-checkbox type="checkbox" class="select_all">Check all</mat- 
checkbox>
<br>
<mat-checkboxtype="checkbox" class="select_single">Check-1</mat-checkbox>
<mat-checkbox type="checkbox" class="select_single">Check-2</mat-checkbox>
<mat-checkbox type="checkbox" class="select_single">Check-3</mat-checkbox>
</form>

当我单击“全部选中”时,我想要;同时检查了check-1,check-2和check-3。我怎样才能做到这一点???谢谢

2 个答案:

答案 0 :(得分:1)

您可以利用mat-checkbox的change事件和[checked]输入属性来实现对所有功能的检查,如下所示:

HTML:

<mat-checkbox (change)="chkAllChange($event)" type="checkbox" class="select_all">Check all</mat-checkbox>
<br/>
<mat-checkbox type="checkbox" class="select_single" [checked]="chkArr[0]">Check-1</mat-checkbox>
<mat-checkbox type="checkbox" class="select_single" [checked]="chkArr[1]">Check-2</mat-checkbox>
<mat-checkbox type="checkbox" class="select_single" [checked]="chkArr[2]">Check-3</mat-checkbox>

TS:

chkArr:boolean[]=[false,false,false];

  chkAllChange(event:MatCheckboxChange){
    if(event.checked){
      this.chkArr = this.chkArr.map(m=>true);
    }
    else{
      this.chkArr = this.chkArr.map(m=>false);
    }
  }

此处演示:https://stackblitz.com/edit/angular-ngjvt8

答案 1 :(得分:1)

您可以执行以下操作。在html

<table class="table">
          <thead class="green-color">
          <tr>
            <th>
                <input type="checkbox" (change)="checkAll($event)">
            </th>
          </tr>
          </thead>
          <tbody>
          <tr *ngFor="let list of orders">
            <td>
              <input type="checkbox" value="{{list.number}}" [(ngModel)]="list.isChecked">
            </td>
          </tr>
          </tbody>
</table>

以及您的.ts文件中

checkAll(event) {
    this.orders.forEach(object => object.isChecked = event.target.checked);
  }