Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 284
Tarnjeet Singh Avatar asked Mar 11 '26 18:03

Tarnjeet Singh


2 Answers

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.

like image 105
Kristiyan Petrov Avatar answered Mar 14 '26 08:03

Kristiyan Petrov


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()
 });
like image 44
Chintan Joshi Avatar answered Mar 14 '26 09:03

Chintan Joshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!