6

I have a problem with Reactive forms. Updating the model class when the User changes the input is straight forward. But I need to do the opposite way: programmatically change the model, and see the changes in the HTML form.

The simplified code is:

this.user = new User();

And then:

this.form = this.fb.group({
      name: new FormControl(this.user.name, [Validators.required]),
      email: new FormControl(this.user.email, [Validators.required])    
    });

Assume that it is working fine. If the user updates the name in the GUI the this.user.name is being correctly updated.

Assume that I have added some logic to User class, that populates the email based on the entered name. Every time the name changes, the email field is auto-generated as 'name'@gmail.com

Unfortunately the generated email is not visible in the GUI. How to achieve that?

How to notify the FormGroup about changes in the User class?

I had two ideas:

1) Add ([ngModel]) - and it worked - but I feel that it is a bad idea to mix Reactive Forms with ngModel

2) Add the following code, after the form is created:

this.form.controls["name"].valueChanges.distinctUntilChanged().subscribe(form => {
    this.form.patchValue({email: this.model.email});
});

But it does not look clean. Is there any other option?

3
  • use (valueChanged)="someMethod($event)" . Commented Jun 10, 2018 at 11:28
  • What does a console.log(this.model.email) print in the subscription? Commented Jun 10, 2018 at 11:35
  • sorry, my bad - not model but this.user.email :) Commented Jun 10, 2018 at 11:37

1 Answer 1

4

That's just not how reactive forms are intended to work.

With reactive forms, the form is not bound to your model, it has its own model, which you can see if you look at "form.value".

The value that you pass to the form control as you are creating it is not bound, it's just used as an initial value for the form control.

The intention is that the user fills out the form, validations happen dynamically (that's the reactive part), and then when they submit the form, you transfer the form's value to your model, all at once.

That said, if you want to update the value of a form control, patchValue is indeed the correct way to do it.

Sign up to request clarification or add additional context in comments.

2 Comments

So ... if I need to make such interaction as model -> HTML form I should stick to template driven forms and two-way databinding ?
I suppose so, but I can't imagine a use case where you "need" to bind your form directly to your model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.