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

2

9

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?

Cazares answered 2/6, 2021 at 10:55 Comment(1)
That shouldn't happen. You sure you don't have 2 subscriptions open? In the first sample I don't see you unsubscribing, so each time you reload your page a new subscription is created. If this still is an issue, please reproduce the issue in for example a stackblitz.Scot
B
9

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.

Boche answered 22/7, 2021 at 9:19 Comment(0)
S
3

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()
 });
Smetana answered 2/6, 2021 at 11:2 Comment(3)
I have already used it , just forgot to mention. I have updated the questionCazares
If it detects changes once by using distinctUntilChanged but still delayed, remove debounce & just use distinctUntilChanged.Smetana
I have used distinctUntilChanged only, so called valuechanges method called twice time.Topsail

© 2022 - 2024 — McMap. All rights reserved.