Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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([])
      });
  }
} 
like image 918
Tarnjeet Singh Avatar asked Nov 07 '17 05:11

Tarnjeet Singh


People also ask

What is FormArray in Angular?

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.


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

like image 105
user1533603 Avatar answered Sep 17 '22 20:09

user1533603


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;
        } 
like image 32
i3lai3la Avatar answered Sep 19 '22 20:09

i3lai3la