I am working on Angular 4 project. I have a requirement to detect the changes of form control array. e.g. I have a form control array named providers, how to detect its changes?
export class CustomFormArray {
public form: FormGroup;
constructor(private _fb: FormBuilder) {
this.form = _fb.group({
providers: _fb.array([])
});
}
}
A FormArray aggregates the values of each child FormControl into an array. It calculates its status by reducing the status values of its children. For example, if one of the controls in a FormArray is invalid, the entire array becomes invalid.
FormArray
extends AbstractControl
so it has valueChanges
property which emits chanes.
this.form = this.fb.group({
providers: this.fb.array([]),
});
(this.form.get('providers') as FormArray).push(new FormControl('', Validators.required));
(this.form.get('providers') as FormArray).push(new FormControl('', Validators.required));
(this.form.get('providers') as FormArray).valueChanges.subscribe(values => {
console.log(values);
});
In your template:
<input *ngFor="let field of form.controls.providers.controls;" [formControl]="field">
The values
in subscribe will return a array with value of each input field when any of changes(grammatically or from UI).
In case of if there are FormGroup
in FormArray
nothing changes. just use following component code.
(this.form.get('providers') as FormArray).push(this.fb.group({
'name': '',
'age': ''
}));
and template will be:
<div *ngFor="let field of form.controls.providers.controls;" [formGroup]="field">
<input formControlName="name" placeholder="name">
<input formControlName="age" placeholder="age">
</div>
here is plunker
Is similar as how you do it for normal form group. Whenever you initialize form group of your form array, just emit/subscribe change event your form group of your form array.
here is the sample.
export class CustomFormArray {
public form: FormGroup;
constructor(private _fb: FormBuilder) {
this.form = _fb.group({
providers: _fb.array([])
});
this.providers.push(this.createprovidersFormGroup())
}
createprovidersFormGroup(){
let form = this._formBuilder.group({
abc: "abc"
});
form.valueChanges.subscribe(data => {
console.log('Form changes', data)
});
return form;
}
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