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

查看:26
本文介绍了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.

推荐答案

您可以使用合并运算符将 3 个单独的 observable 合并为一个.这将为您提供一个单一的 observable,它会在任何表单字段值发生变化时发出单一值.

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

这将给出一个可在任何字段更改时发出的 observable,并且它发出的值将是一个包含该值和发出该值的控件的对象.

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天全站免登陆