Search code examples
angularangular4-forms

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


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

Solution

  • 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