Vingtoft
Vingtoft

Reputation: 14606

Angular2: Detect form changes

In Angular2 4.0 I have a FormGroup looking like this:

this.form = this._fb.group({
      a: ['', [Validators.required]],
      b: ['', [Validators.required]],
      c: ['', [Validators.required]],
    });

Is it possible to subscribe valueChanged on individual fields?

I dont want to detect changes on input c, so the below approach does not work:

this.form.valueChanges.debounceTime(400).subscribe(data => {
     // Do something
    });

Upvotes: 5

Views: 14904

Answers (3)

H.Azizkhani
H.Azizkhani

Reputation: 923

          this.form.valueChanges
            .pipe(
              debounceTime(500), // Wait for 0.5
              distinctUntilChanged() //  execute only if a different value is emitted
            )
            .subscribe((newForm) => {
              console.log(newForm);
            });

Upvotes: 0

Sujith S
Sujith S

Reputation: 601

  
//get form ref  
@ViewChild('myForm') myForm;

//implement afterview init to your class and use
// or you can use same code with ngOnInit

ngAfterViewInit(){
  this.myForm.valueChanges.debounceTime(500).subscribe(data =>            console.log('Form changes', data));
}

You can use this code, it will give you changed field data also.

Upvotes: 4

tottomotto
tottomotto

Reputation: 2352

You can add separate subscriptions for FormControl a and b.

this.heroForm.controls["a"].valueChanges.subscribe(data => {
 // Do something
});

this.heroForm.controls["b"].valueChanges.subscribe(data => {
 // Do something
});

Upvotes: 8

Related Questions