Jay
Jay

Reputation: 153

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="{{i}}"/>
          <div class="unit-number">{{ unit.num }}</div>
          <div class="unit-desc">{{ 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 {}

Upvotes: 4

Views: 9287

Answers (1)

AVJT82
AVJT82

Reputation: 73337

Making a combination of the comments provided by Rahul and ncohen we can use patchValue here.

As for the unselecting all checkboxes, I changed it to a button in this answer, to me it seemed that a checkbox wasn't really suitable (?) because of handling the tick in the checkbox. But that is up to you if you rather use a checkbox :)

As for checking if the "Select All" checkbox should be checked or not, you can do:

[checked]="checkAllSelected()"

and then in TS:

checkAllSelected() {
  return this.form.controls.unitArr.controls.every(x => x.value == true)
}

Here we then must remember that this is run on each change detection. So perhaps you'd want to use a variable instead, that is of course depending on the case, i.e how costly this would be for you, but I don't think it would be in this case.

So this is how your template could look like:

<label>
   <input type="checkbox" [checked]="checkAllSelected()" 
         (click)="selectAll($event.target.checked)"/>Select all
</label>
<button (click)="unselectAll($event.target.checked)">Unselect All</button>

where we pass the status of the checkbox to template and evalate to either check all or uncheck all:

selectAll(isChecked) {
  if isChecked 
     this.form.controls.unitArr.controls.map(x => x.patchValue(true))
  else
     this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

And of course when user clicks the uncheck button:

unselectAll() {
  this.form.controls.unitArr.controls.map(x => x.patchValue(false))
}

DEMO: http://plnkr.co/edit/O194WEimjf3XzfiIrWF0?p=preview

Upvotes: 4

Related Questions