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

Viewed 25315

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([])
      });
  }
} 
2 Answers

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