How to detect changes in a form control array in Angular 4?

I am working on an Angular 4 project. I have a requirement to detect changes to the form control array. For example, I have an array of form control with the names of suppliers, how to determine its changes?

export class CustomFormArray { public form: FormGroup; constructor(private _fb: FormBuilder) { this.form = _fb.group({ providers: _fb.array([]) }); } } 
+5
source share
2 answers

FormArray extends AbstractControl , so it has a valueChanges property that 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"> 

values in the subscription will return an array with the value of each input field for any changes (grammatically or from the user interface).

In case FormGroup in FormArray nothing changes. just use the following component code.

 (this.form.get('providers') as FormArray).push(this.fb.group({ 'name': '', 'age': '' })); 

and the 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 plunker

+2
source

It seems like you are doing this for a normal group of forms. Whenever you initialize the form group of your form array, simply enter emit / subscribe change event into your form group of your form array.

here is a 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; } 
0
source

Source: https://habr.com/ru/post/1273158/


All Articles