2

<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"]

0

2 Answers 2

9

Its a workaround in angular 2 you canrefer below code 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>

Component

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;
      })
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This approach won't work when the data is coming from API request.
0

In your html

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

In typescript Component

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.