我有反应式表单的问题。当用户更改输入时更新模型类是直接的。但我需要做相反的方式:以编程方式更改模型,并查看 HTML 表单中的更改。
简化的代码是:
this.user = new User();
Run Code Online (Sandbox Code Playgroud)
进而:
this.form = this.fb.group({
name: new FormControl(this.user.name, [Validators.required]),
email: new FormControl(this.user.email, [Validators.required])
});
Run Code Online (Sandbox Code Playgroud)
假设它工作正常。如果用户在 GUI 中更新名称,this.user.name则正确更新。
假设我已经向 User 类添加了一些逻辑,它根据输入的名称填充电子邮件。每次名称更改时,电子邮件字段都会自动生成为“名称” @gmail.com
不幸的是,生成的电子邮件在 GUI 中不可见。如何做到这一点?
如何通知FormGroupUser 类中的变化?
我有两个想法:
1) 添加 ([ngModel]) - 它有效 - 但我觉得将 Reactive Forms 与 ngModel 混合是一个坏主意
2)在创建表单后添加以下代码:
this.form.controls["name"].valueChanges.distinctUntilChanged().subscribe(form => {
this.form.patchValue({email: this.model.email});
});
Run Code Online (Sandbox Code Playgroud)
但看起来并不干净。还有其他选择吗?