Angular 4选中所有复选框

时间:2018-11-28 14:19:16

标签: javascript angular select checkbox

我正在尝试实施全选复选框,这将选择所有复选框,但是当我单击除全选之外的其他复选框时 它将再次选中所有复选框

HTML文件

<div class="form-check mt-3">
  <label class="form-check-label text-dark font-weight-bold">
                <input class="form-check-input" type="checkbox" value="" [(ngModel)]="selectedAll" [ngModelOptions]="{standalone:
       true}" (change)="selectAll()">
                Select All
                <span class="form-check-sign">
                <span class="check"> </span>
              </span>
              </label>
</div>

<div *ngFor="let a of name">

  <div class="d-flex justify-content-between">

    <!--------------------div to justify content --------------------->
    <div class="">

      <div class="form-check mt-3">
        <label class="form-check-label text-dark">
                    <input class="form-check-input" type="checkbox" value="" [(ngModel)]="a.selected" [ngModelOptions]="{standalone:
       true}" (change)="checkIfAllSelected()">
                    Household Information
                    <span class="form-check-sign">
                <span class="check"> </span>
              </span>
                  </label>
      </div>

      <div class="form-check mt-3">
        <label class="form-check-label text-dark">
                    <input class="form-check-input" type="checkbox" value="" [(ngModel)]="a.selected" [ngModelOptions]="{standalone:
       true}" (change)="checkIfAllSelected()">
                    House Images
                    <span class="form-check-sign">
                <span class="check"> </span>
              </span>
                  </label>
      </div>

      <div class="form-check mt-3">
        <label class="form-check-label text-dark">
                    <input class="form-check-input" type="checkbox" value="" [(ngModel)]="a.selected" [ngModelOptions]="{standalone:
       true}" (change)="checkIfAllSelected()">
                    Map Access
                    <span class="form-check-sign">
                <span class="check"> </span>
              </span>
                  </label>
      </div>
    </div>

Ts文件

selectAll() {
  for (let i = 0; i < this.name.length; i++) {
    {
      this.name[i].selected = this.selectedAll;
    }
  }
}

checkIfAllSelected() {

  console.log(this.name);

  this.selectedAll = this.name.every(function(item: any) {
    console.log(item);
    return item.selected == true;
  })

}

1 个答案:

答案 0 :(得分:0)

删除[ngModelOptions]="{standalone: true}",它应该可以工作。 有关更多信息,请参见this链接。