[英]Angular 2 Reactive Forms only get the value from the changed control
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. 表单非常大,因此将每个控件订阅到valueChanges都不是一种选择。
The function currently looks like this: 该功能目前看起来像这样:
checkForValueChanges() {
this.metadataForm.valueChanges.subscribe(controls => {
// how to get the changed control form name here ?
});
}
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. 由于项目非常大,我只是做了一个简单的例子来展示我的问题: StackBlitz示例您可以在控制台中看到我得到的结果是所有控件而不是它改变的控件。
this.imagSub = this.imagingForm.valueChanges.pipe(
pairwise(),
map(([oldState, newState]) => {
let changes = {};
for (const key in newState) {
if (oldState[key] !== newState[key] &&
oldState[key] !== undefined) {
changes[key] = newState[key];
}
}
return changes;
}),
filter(changes => Object.keys(changes).length !== 0 && !this.imagingForm.invalid)
).subscribe(
value => {
console.log("Form has changed:", value);
}
);
That subscription became active on ngOnInit and download some data from API (and after that put them into a form field, so I don't need first value [and value == undefined], because of form setting fields by herself) 该订阅在ngOnInit上变为活动状态并从API下载一些数据(之后将它们放入表单字段中,因此我不需要第一个值[和值== undefined],因为自己的表单设置字段)
For me, that solution works fine. 对我来说,这个解决方案很好。 But I guess if you have a form with "that has a huge amount of fields", this method will be even worse than saving subscriptions.
但我想如果你有一个“有大量字段”的表单,这种方法将比保存订阅更糟糕。
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. 我添加了一个订阅数组来处理destroy上的取消订阅。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.