How to watch on few fields changes in long form in Angular 2
Asked Answered
C

2

8

My form has 10 to 15 fields I just want to watch the changes on 2 fields built using form-builder.

Currently i can watch all the fields in the form using the following code :

  export class App {
  constructor(private formBuilder: FormBuilder) {
    this.form = formBuilder.group({
      firstName: 'John',
      lastName: 'Fleming',
      Name: 'John Fleming',
      Address : '12331 wiley post',
      city: '',
      state:'',
      ...... so on    
    })

    this.form.valueChanges.subscribe(data => {
      console.log('Form changes', data)
      this.output = data
    })
  }
}

I don't want to watch all the fields, I used (keyup) event on those fields to handle it for now. But I want to know whether there is any better way of doing the same in angular2?

Chiou answered 11/8, 2017 at 5:1 Comment(0)
H
13

I can't try this right now to confirm the syntax ... but something like this:

import { merge } from 'rxjs';    
merge(
      this.form.get('firstName').valueChanges,
      this.form.get('lastName').valueChanges
    )
     .subscribe(data => console.log(data));
Hydrophobic answered 11/8, 2017 at 5:33 Comment(1)
NOTE: Edited Feb 8, 2021 to bring to current RXJS syntax.Hydrophobic
D
4

you can use this to check on form fields per field

this.form.get('firstName').valueChanges.subscribe(data => console.log(data)); 
Discriminative answered 11/8, 2017 at 5:20 Comment(2)
Thanks Rahul, Is there any way to watch multiple fields like firstname and lastname at a time?Chiou
@Chiou i guess you got your answer by deborah , she is merging the two observables and getting the result , but there is no one way syntax from angularDiscriminative

© 2022 - 2024 — McMap. All rights reserved.