0

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
     }});
Rahul Mukherjee
  • 107
  • 1
  • 1
  • 10
  • Is the form control not defined at this point? If you console.log(this.uiform.get(formControlName)) is it undefined? – Donald Duck Aug 18 '22 at 00:21

2 Answers2

3

Every time your input changes, you are creating a new subscription. Nothing happens at first because no subscriptions exist yet.

Just subscribe to valueChanges once on init. Use a loop if you have multiple.

ngOnInit(){
  this.uiForm.get(this.subControl.name)?.valueChanges.pipe(...).subscribe(...);
}
<input type="text" formControlName='{{subControl.name}}'/>

I'm assuming subControl is a component property, which might not be true. But I'm sure you get the idea.

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26
0

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(...);
RITZ XAVI
  • 3,633
  • 1
  • 25
  • 35