8

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?

1 Answer 1

9
  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/

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly! Thanks. I appreciate the explanation.

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.