2017-08-18 38 views
2

我有一個角度爲2的反應形式,其中包含數據綁定的複選框列表。這工作正常,但現在我需要添加一個按鈕來檢查所有複選框。檢查FormArray - Angular 2 Reactive Form中的所有複選框

我FormGroup被繼承人如何配置:

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); 
    } 

我的繼承人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> 

如何將訪問FormArray設置所有複選框作爲託運?

回答

2
  1. 將formGroupName和formControlName添加到您的模板中。 (讓Angular 2+知道DOM和formGroup結構如何關聯。)
  2. 從模板中刪除[formControl] =「chapter」。 (你不需要這個。)
  3. 在你的模板中添加一個按鈕。
  4. 使用value屬性(獲取有效數組)和setValue方法(將操縱數組反饋回)。

你的模板將是這樣的:

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

您添加到您的類中的方法:

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

一個工作普拉克:http://embed.plnkr.co/8yXBn1DhboiIwRIv7AS0/

+0

完美的作品!謝謝。我讚賞解釋。 – sykespro