Angular 2-在Observable中获取已更改的FormControl的值 [英] Angular 2 - Get the value of changed FormControl in Observable

查看:78
本文介绍了Angular 2-在Observable中获取已更改的FormControl的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用FormBuilder构建的简单表单:

I have a simple Form built with FormBuilder:

this.contactForm = formBuilder.group({
  'name': [''],
  'email': [''],
  'phone': [''],
});

我想监视每个控件的更改,并在发生这种情况时使用更新后的值运行一个函数:

I want to watch every control for changes, and run a function with the updated value when this happens:

getContacts(value: any) {
    this.phoneContacts.findContact(value).then(
        contacts => {
            // do something
        }
    );
}

现在,我正在为每个控件执行此操作,使用bind可以访问组件的this对象:

Right now, I'm doing this for every control, using bind to have access to the this object of the component:

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,但是我得到的不仅仅是控件,而是所有控件的值.

Is there any way to watch for changes and have the updated value with just one subscription? I know I can subscribe directly to this.contact.form, but then instead of just the updated control I get all controls as the value.

推荐答案

您可以使用merge运算符将3个独立的可观察对象合并为一个.这样,您就可以得到一个可观察的对象,该对象在任何一个表单字段值更改时都会发出该值.

You can merge the 3 individual observables into one using the merge operator. That will give you a single observable that emits the single value any time any one of the form field values changes.

this.contactForm.get('name').valueChanges
    .merge(this.contactForm.get('email').valueChanges)
    .merge(this.contactForm.get('phone').valueChanges)

上述方法的主要问题是您现在不知道哪个值与哪个窗体控件一起使用.一种解决方案是将值更改映射到同时包含值和控件(即值的源)的另一个对象中

The main problem with the approach above is that you now don't know which value goes with which form control. One solution is to map the value changes into another object that contains both the value and the control (i.e. the source of the value)

// 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}))  

这将提供一个可观察到的值,该值在任何字段发生更改时都将发出,并且它发出的值将是一个包含该值和发出该值的控件的对象.

This will give an observable that emits whenever any of the fields change, and the value it emits will be an object containing the value and the control that emitted that value.

这篇关于Angular 2-在Observable中获取已更改的FormControl的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆