FormBuilder and FormArray are used for developing complex forms by reactive model approach in Angular 2.
In complex forms usually we have dynamic grouping of controls based on business needs, For example populating the dynamic check boxes list and storing the states(checked/unchecked).
FormArray – Array of FormControl instances.
FormArray holds the aggregated behavior, like if any child control inside FormArray is in invalid sate then FormArray instance will be invalid too.
Formbuilder– like an helper utility which we use to create instances (FormControl, FormGroup) without using new keyword.
Creating a FromArray using FormBuilder.
To use FormBuilder we have to inject he FormBuilder instance at component constructor level.
at component level:
import { FormBuilder, FormArray} from '@angular/forms'; selectedCheckboxIds: FormArray; constructor(private fb:FormBuilder) { this.selectedCheckboxIds: this.fb.array([]); }
Below some Array operations on FormArray:
- To add FormControl instances dynamically using push.
this.selectedCheckboxIds.push(new FormControl("abc"));
- To check existing control/value in the FormArray using filter.
this.selectedCheckboxIds.controls.filter(c => c.value == "abc").length > 0)
- Remove the existing control from FormArray using removeAt.
this.selectedCheckboxIds.controls.forEach((item, index) => { if (item == this.selectedCheckboxIds.controls.filter(c => c.value == "abc")[0]) this.selectedCheckboxIds.removeAt(index); });
** We can also use splice method to remove the control element.