POV
POV

Reputation: 12015

How to notify that element form was changed?

I have some forms are generated by FormGroup.

class FormGroupCustom {
    form: FormGroup;
}

let forms: FormGroupCustom[] = [];

for(let i = 0; i <= 10; i++) {
   this.forms.push({"formName": i, "form": new FormGroup()});
} 

How can I notify formName: 1 from array this.forms that any field was changed from formName: 2.

I have tried to apply Observer pattern, because I dont need to use reactive nested forms.

My solution is:

class Notify {

     notifyChange(formName: string, valueField: any) {
             // FIND form in array forms by formName
     }

}

Then apply ng-change on specific element if form like:

<input type="text" (ngChange)="change('formName1', 'value')"


change(formName: string, value: any) {
    let notify = new Notify();
    notify.notifyChange(formName, value);
} 

So notifyChange can find form in array forms than do action over specific field in this form

Upvotes: 1

Views: 653

Answers (1)

terahertz
terahertz

Reputation: 3491

for(let i = 0; i <= 10; i++) {
  this.forms.push({formName: i, form: new FormGroup({}) });
  let s = this.forms[i].form.valueChanges.subscribe(val => {
    // do something when form control changes
  })

  this.subs.push(s)
}

There is a valueChanges() observable that you can subscribe to, to do something when the value of a form changes, is that what you are looking for?

Stackblitz Example

Upvotes: 1

Related Questions