typescript - Check all checkboxes within a FormArray - Angular 2 Reactive Form -


i have angular 2 reactive form list of checkboxes data bound. works fine, need add button check checkboxes.

heres how formgroup 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 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 access formarray set checkboxes checked?

  1. add formgroupname , formcontrolname template. (to let angular 2+ know how dom , formgroup structure relates.)
  2. delete [formcontrol]="chapter" template. (you don't need this.)
  3. add button template.
  4. use the value property (to valid array) , setvalue method (to feed manipulated array back).

your template this:

<div class="form-group" formgroupname="groupchapters">     <label for="">select chapters</label>     <div *ngfor="let chapter of formchapters.controls; let = index" class="checkbox">         <label>             <input type="checkbox" formcontrolname="{{i}}">             {{chapters[i].title}}         </label>     </div>     <button (click)="checkall()">check all</button> </div> 

the method add class:

private checkall() {     this.groupform.controls['groupchapters'].setvalue(         this.groupform.controls['groupchapters'].value             .map(value => true);     ); } 

a working plunk: http://embed.plnkr.co/8yxbn1dhboiiwriv7as0/


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -