How to correctly 2-way-bind with reactive forms?

2019-07-14 18:37发布

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.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-07-14 19:19

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

查看更多
Melony?
3楼-- · 2019-07-14 19:19

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)"/>
查看更多
登录 后发表回答