Angular 2 Reactive Forms 仅从更改的控件中获取值 [英] Angular 2 Reactive Forms only get the value from the changed control

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

问题描述

我有一个包含所有输入的动态创建的表单.我订阅了更改,但是当更改控件时,我会从所有控件中获取值,因此我真的不知道更改了哪个控件.是否可以使用 valueChanges 函数仅从更改后的控件中获取更改后的值?

I have a dynamically created form with all inputs. I am subscribing for changes, but when a control is changed I get the values from all the controls, so I don't really know which one is changed. Is it possible to get the changed value only from the changed control with the valueChanges function?

表单非常大,因此无法为每个控件订阅 valueChanges.

The form is pretty big, so subscribing every control to valueChanges is not an option.

该函数目前看起来像这样:

The function currently looks like this:

checkForValueChanges() {
    this.metadataForm.valueChanges.subscribe(controls => {
        // how to get the changed control form name here ?
    });
}

由于项目真的很大,我就简单的举个例子来说明我的问题:StackBlitz 示例您可以在控制台中看到,我得到的结果是所有控件,而不仅仅是更改的控件.

Since the project is really big, I just made a simple example to show my issue: StackBlitz example You can see in console that the result I get is all of the controls instead of just the one it's changed.

推荐答案

我能想到的最简洁的方式是动态订阅所有表单控件:

The cleanest way I can imagine is to subscribe dynamicaly to all the form controls :

const subscriptions = [];
for (const key of Object.keys(this.metadataForm.controls)) {

    const subscription = this.metadataForm.controls[key].valueChanges
    .subscribe(value => console.log('value :' + value[key] + ' and key : ' + key));

    subscriptions.push(subscription);
}

我添加了一组订阅来处理销毁时的取消订阅.

I added an array of subscriptions to handle the unsubscribe on destroy.

这篇关于Angular 2 Reactive Forms 仅从更改的控件中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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