Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check all checkboxes within a FormArray - Angular 2 Reactive Form

I have an angular 2 reactive form with a list of checkboxes that are data bound. This works fine, but now I need to add a button to check all checkboxes.

Heres how my FormGroup is configured:

  private buildForm() {
    this.groupForm = this._formBuilder.group({
      bookId: this._formBuilder.control(null),
      startDate: this._formBuilder.control(null),
      groupTotal: this._formBuilder.control(null),
      chapterGrouping: this._formBuilder.control("all"),
      groupChapters: this.buildChapters()
    });
  } 

  private buildChapters() {
    const chapters = this.chapters.map(chapter => {
      return this._formBuilder.control(chapter.selected)
    });
    return this._formBuilder.array(chapters);
  }

Heres my HTML:

<div class="form-group">
    <label for="">Select chapters</label>
    <div *ngFor="let chapter of formChapters.controls; let i=index" class="checkbox">
        <label>
        <input type="checkbox"  [formControl]="chapter" >
        {{chapters[i].title}}
        </label>
    </div>
</div>

How would I access the FormArray to set all checkboxes as checked?

like image 827
sykespro Avatar asked Aug 18 '17 02:08

sykespro


1 Answers

  1. Add a formGroupName and a formControlName to your template. (To let Angular 2+ know how the DOM and the formGroup structure relates.)
  2. Delete [formControl]="chapter" from your template. (You don't need this.)
  3. Add a button to your template.
  4. Use the the value property (to get a valid array) and the setValue method (to feed the manipulated array back).

Your template will look like this:

<div class="form-group" formGroupName="groupChapters">
    <label for="">Select chapters</label>
    <div *ngFor="let chapter of formChapters.controls; let i = index" class="checkbox">
        <label>
            <input type="checkbox" formControlName="{{i}}">
            {{chapters[i].title}}
        </label>
    </div>
    <button (click)="checkAll()">Check all</button>
</div>

The method you add to your class:

private checkAll() {
    this.groupForm.controls['groupChapters'].setValue(
        this.groupForm.controls['groupChapters'].value
            .map(value => true);
    );
}

A working Plunk: http://embed.plnkr.co/8yXBn1DhboiIwRIv7AS0/

like image 200
Koudela Avatar answered Nov 10 '22 02:11

Koudela