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?