I've a big form and would like to listen to the changes of 5 specific fields .
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.
Previous :
Use merge from 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.