我有一个简单的表单FormBuilder
:
this.contactForm = formBuilder.group({
'name': [''],
'email': [''],
'phone': [''],
});
我想观察每个控件的更改,并在发生这种情况时使用更新后的值运行函数:
getContacts(value: any) {
this.phoneContacts.findContact(value).then(
contacts => {
// do something
}
);
}
现在,我正在为每个控件执行此操作,使用bind
能够访问this
组件的对象:
this.contactForm.get('name').valueChanges.subscribe(this.getContacts.bind(this));
this.contactForm.get('email').valueChanges.subscribe(this.getContacts.bind(this));
this.contactForm.get('phone').valueChanges.subscribe(this.getContacts.bind(this));
有没有什么方法可以观察变化并仅通过一次订阅即可获得更新的值?我知道我可以直接订阅this.contact.form
,但随后我将所有控件作为值,而不只是更新的控件。
您可以使用合并运算符将 3 个单独的可观察量合并为一个。这将为您提供一个可观察的值,只要任何一个表单字段值发生变化,它就会发出单个值。
this.contactForm.get('name').valueChanges
.merge(this.contactForm.get('email').valueChanges)
.merge(this.contactForm.get('phone').valueChanges)
上述方法的主要问题是您现在不知道哪个值与哪个表单控件对应。一种解决方案是将值更改映射到另一个包含该值和控件(即值的来源)的对象
// making some local variables for convenience
let name = this.contactForm.get('name')
let email = this.contactForm.get('email'
let phone = this.contactForm.get('phone')
name.valueChanges.map(v => ({control: name,value: v})
.merge(email.valueChanges.map(v => ({control: email, value: v}))
.merge(phone.valueChanges.map(v => ({control: phone, value: v}))
这将给出一个每当任何字段发生变化时都会发出的可观察对象,并且它发出的值将是一个包含该值和发出该值的控件的对象。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)