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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With