2

So far I've always seen that you shouldn't mix using [(ngModel)] with reactive forms, and instead simply use formControlName.

However, for me it doesn't seem to be working?

I have a form and I add controls to it

this.exportForm.addControl("surcharge", new FormControl(this.details.SurchargeExtraField));

and in my html I give the input the formControlName

    <div class="col-sm-12 col-md-6">
        <input type="text" formControlName="surcharge" />
    </div>

However when I use the input it doesn't change anything about this.details.SurchargeExtraField, it only works for validation.

When I do:

<input type="text" formControlName="surcharge" [(ngModel)]="details.SurchargeExtraField" />

It works perfectly, but appareantly it's not the correct way.

amphetamachine
  • 27,620
  • 12
  • 60
  • 72
Nicolas
  • 4,526
  • 17
  • 50
  • 87

2 Answers2

0

You can listen to the form changes by using this

  this.exportForm.valueChanges.subscribe((form) => {
     console.log(form);
   });

For more info on reactive form check this LINK

The same is applicable for any FormControl in the form you can look for changes and act accordingly

Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • so "automatic" 2-way-binding like `[(ngModel)]` does is not possible with reactive forms? – Nicolas Sep 07 '17 at 07:51
  • you get the binding done if you see that example link the form is getting updated dynamically but it is not like ngModel but using observables on formControl – Rahul Singh Sep 07 '17 at 07:52
0

You can listen for form changes like this

this.exportForm.valueChanges.subscribe((changes) => {
     console.log(changes);
});

or you can listen for formcontrol changes like this

this.exportForm.get('surcharge').valueChanges.subscribe((change) => {
     console.log(change);
});

or you can do this

onChange (newVal) {
   console.log(newVal);
}

<input type="text" formControlName="surcharge" #surchargeInput (change)="onChange(surcharge.target.value)"/>
Yordan Nikolov
  • 2,598
  • 13
  • 16
  • "there's no reason to not mix formControlName and ngModel like this" - Except the fact that behavior is deprecated in Angular 6, and will be gone in Angular 7. – amphetamachine Dec 05 '18 at 21:45
  • 1
    You are completely right, but at the time I answered it was possible. So I'm gonna edit my answer now. – Yordan Nikolov Jan 07 '19 at 14:02