mercredi 9 août 2017

Angular 2 Select/unselect all checkbox

i want to select/unselect all checkbox. i tried refering other code but nothing worked for me

below is my code. selecting unseleting particular unit is working for me. basically when i clicks on div it selects/unselects checkbox and adds color to it. but i am confused with select all/unselect all

please help me to do it with my code

//our root app component
import {Component, NgModule, VERSION} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { ReactiveFormsModule, FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
  <form [formGroup]="form">
    <div formArrayName="unitArr">
    <label><input type="checkbox" />Select all</label>
    <label><input type="checkbox" />unSelect all</label>
      <div 
        *ngFor="let unit of units; let i = index"
        class="unit"
        (click)="onClick(i)"
        [ngClass]="{'unit-selected': unitArr.controls[i].value}">
          <input type="checkbox" formControlName=""/>
          <div class="unit-number"></div>
          <div class="unit-desc"></div>
      </div>
    </div>
  </form>
  `,
  styles: [`.unit-selected { color: red; }`]
})
export class App implements OnInit{
  private units = [
    {num: 1, desc: 'Decription'},
    {num: 2, desc: 'Decription'},
    {num: 3, desc: 'Decription'},
  ];
  private form: Form;
  
  constructor (private fb: FormBuilder) {}
  
  ngOnInit () {
    this.form = this.fb.group({
      unitArr: this.fb.array(
        this.units.map((unit) => {
          return this.fb.control(false); // Set all initial values to false
        })
      )
    });
  }
  
  // Shorten for the template
  get unitArr (): FormArray {
    return this.form.get('unitArr') as FormArray;
  }

  onClick(i) {
    const control = this.unitArr.controls[i];
    control.setValue(!control.value); // Toggle checked
  }
}

@NgModule({
  imports: [ BrowserModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}



Aucun commentaire:

Enregistrer un commentaire