Reactive forms valueChanges method fires twice for one change on input fields

Viewed 2932

Am working in angular app, where used the valueChanges method to detect the changes. like :

this.MyFrm.controls['is_applicable'].valueChanges.subscribe(values => {
  this.mainFunc()       
});

But it trigger this function twice, To solve this, I have used debounceTime. like :

 this.MyFrm.controls['is_applicable'].valueChanges.pipe(debounceTime(0),distinctUntilChanged(),takeUntil(this.destroy$)).subscribe(values => {
   this.mainFunc()
 });

But now problem is occur that valueChanges trigger after some time, that break my code flow.

Any Suggestion?

2 Answers

Try using distinctuntilchanged which is one of the rxjs operators. It will return unique values only.

 this.MyFrm.controls['is_applicable'].valueChanges.pipe(distinctUntilChanged()).subscribe(values => {
    this.mainFunc()
 });

If you want to take only first response and keep listening for changes on the Reactive Form with distinctUntilChanged(), you can use throttleTime(500), this will emit the first value and then ignore next response for 0,5s.

this.MyFrm.controls['is_applicable'].valueChanges
    .pipe(
      distinctUntilChanged(),
      throttleTime(500),
      takeUntil(this.destroy$)
    )
    .subscribe(values => {
      this.mainFunc()
 });

EDIT: Your form field 'is_applicable' for some reason has two Subscribers and that's why is occur to return two times same response.

Related