如何选择角度2中的所有复选框?

时间:2017-07-05 18:32:43

标签: angular

<div class="col-2">
  <label class="myButton btn btn-default"><input  type="checkbox" [checked]="selectAllCheckbox" (click)="selectAll()"> Select All</label>
</div>
<div class="row">
  <div class="col-2" *ngFor="let user of Users; let idx = index">
    <label><input [checked]="item._selected" (click)="updatedUserList(user, $event)" type="checkbox"> {{user}}</label>
  </div>
</div>

users = [“users1”,“users2”,“users3”]

2 个答案:

答案 0 :(得分:7)

你可以在代码下面找到角度2的变通方法 HTML

<ul>
  <li> <input type="checkbox" [(ngModel)]="selectedAll" (change)="selectAll();"/>
  </li>
  <li *ngFor="let n of names"> 
  <input type="checkbox" [(ngModel)]="n.selected" (change)="checkIfAllSelected();">
  {{n.name}}
  </li>
</ul>

组件

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title: String;
  names: any;
  selectedAll: any;
  constructor() {
    this.title = "Select all/Deselect all checkbox - Angular 2";
    this.names = [
      { name: 'Prashobh', selected: false },
      { name: 'Abraham', selected: false },
      { name: 'Anil', selected: false },
      { name: 'Sam', selected: false },
      { name: 'Natasha', selected: false },
      { name: 'Marry', selected: false },
      { name: 'Zian', selected: false },
      { name: 'karan', selected: false },
    ]

  }
  selectAll() {
    for (var i = 0; i < this.names.length; i++) {
      this.names[i].selected = this.selectedAll;
    }
  }
  checkIfAllSelected() {
    this.selectedAll = this.names.every(function(item:any) {
        return item.selected == true;
      })
  }
}

答案 1 :(得分:0)

在您的html

   <div *ngFor="let user of Users">
      <input type="checkbox" [(ngModel)]="user.selected" (change)="ToggleChb();">
   </div>

在打字稿组件中

   ToggleChb(state:boolean){
     this.Users.forEach(user=> user.selected = state)
   }