[英]Angular 2+: how to subscribe to form valueChanges of whitelisted fields?
I've a big form and would like to listen to the changes of 5 specific fields . 我有一个大的形式 , 想听 5个特定领域 的变化 。
I can listend to the entire form: 我可以听完整的表格:
this.form.valueChanges.subscribe(data => {
// do something, because any field changed
});
or to a single field: 或到单个字段:
this.form.get('my_single_field').valueChanges.subscribe(data => {
// do something, because my_single_field changed
});
Desired: 期望:
but I would like to have something like: 但我想要这样的东西:
this.form.get(['field1', 'field5']).valueChanges.subscribe(data => {
// do something, because field1 or field5 changed
});
or: 要么:
this.form.valueChanges.subscribe(data, changedField => {
// do something, because changedField changed
});
Any idea? 任何想法? Thanks! 谢谢!
Edit: 编辑:
You can add below function as prototype on Form. 您可以在Form上添加以下功能作为原型。
Previous : 上一个 :
Use merge from rxjs. 使用来自rxjs的合并 。 Function should be like this. 功能应该是这样的。
function listenChangesOn(form,fields:string[]){
return Observable.merge(fields.map(field=>form.get(field).valueChanges))
}
and can use like 并可以使用像
listenChangesOn(form,['field1','field2']).subscribe(a=>..)
I faced a similar issue. 我遇到了类似的问题。 I wanted to listen the entire form except one field, and solved by listening the entire form as you do, and inside the observer function put a conditional asking if this field is touched. 我想听除一个字段之外的整个表单,然后像您一样通过听整个表单来解决问题,并在观察者函数中放一个条件询问该字段是否被触摸。 Would be something like this: 将是这样的:
this.form.valueChanges.subscribe(data => {
if (this.form.controls['field1'].touched) return;
// do something, because any other field changed
});
Of course you can do the inverse way, by listening the specific fields you need. 当然,您可以通过侦听所需的特定字段来执行相反的操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.