Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Valuechanges not firing first time

I have a input button, where onChange, I am calling a function. In that funtion, I am checking for valueChanges. Somehow, the subscribe to the valueChanges is not getting triggered on the first tab out after inputting a value.

Here are some code snippets: HTML:

<input type="text" formControlName='{{subControl.name}}' 
(change)="fetchData(subControl.name, 
 true)"/>

TS:

public fetchData(formControlName: string, fetchData: boolean): void {
if (this.primaryControls.indexOf(formControlName) !== -1 && 
   fetchData) {
  this.uiForm.get(formControlName)?.valueChanges **//fine till here. Gets executed**
    .pipe(
      debounceTime(1000)
    )
    .subscribe(data => { **// This subscribe is not firing**
      if (!this.uiForm.dirty) {
        return;
      }
         //do some stuff here
     }});
like image 802
Rahul Mukherjee Avatar asked May 14 '26 17:05

Rahul Mukherjee


1 Answers

You can make use of startWith() with some initial value inside your pipe to fire the subscription the first time.
You can optionally include distinctUntilChanged() in the pipe as well.

this.uiForm.get(this.formControlName)?.valueChanges.pipe(debounceTime(1000), distinctUntilChanged(), startWith(this.uiForm.get(this.formControlName).value)).subscribe(...);
like image 70
RITZ XAVI Avatar answered May 16 '26 13:05

RITZ XAVI



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!