0

i want when use input data after 300 millisecond emit data for doing this i using the debouceTime :

subject: Subject<any> = new Subject();

constructor(private formBuilder: FormBuilder) { }

ngOnInit();

sendValue(): void {
 this.subject.pipe(debounceTime(300))
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.value);
  })
}

and this is html :

  <input
     (change)="sendValue()"
     required
     [formControlName]="controls.controlName"
     matInput
  />

but it not execute subscribe after 300 millisecond .

whats the problem ? how can i solve this problem ???

kianoush dortaj
  • 411
  • 7
  • 24

2 Answers2

1

You're creating a RxJS Subject observable and subscribing to it directly. Unless any value is pushed to it, it won't emit. Using an external observable is unwarranted in this situation.

What you could do is to use the valueChanges observable of the FormControl. You don't need the binding to change event as well. The valueChanges will emit anytime the value of the element changes since it's a FormControl element.

Try the following

Control

ngOnInit() {
  ...
  this.controls.controlName.valueChanges.pipe(          // <-- form control here
    debounceTime(300)
  )
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.value);
  });
}

Template

<input
   required
   [formControlName]="controls.controlName"
   matInput
/>

Update: combine multiple observable

If you have multiple controls, one way would be to combine all the valueChanges observables using RxJS merge function.

ngOnInit() {
  ...
  merge(
    this.controls.controlName.valueChanges,  
    this.controls.controlPhone.valueChanges,  
    this.controls.controlId.valueChanges,
    ...  
  ).pipe(
    debounceTime(300)
  )
  .subscribe(() => {
    this.formValue.emit(this.dynamicForm.value);
  });
}
ruth
  • 29,535
  • 4
  • 30
  • 57
1
  • Use (input) instead of (change). Why? check here
  • You should call .next() on Subject, then only streaming continues and .subscribe() will get new data

HTML

<form [formGroup]="fg">
  <input type="text" formControlName="firstname" (input)="sendValue()">
  <input type="text" formControlName="lastname" (input)="sendValue()">
</form>

TS

export class AppComponent implements OnInit {
  fg: FormGroup;
  inputSubject = new Subject();

  constructor(
    private fb: FormBuilder,
  ) {}

  public ngOnInit() {
    this.fg = this.fb.group({
      firstname: '',
      lastname: '',
    });

    this.inputSubject
      .pipe(
        debounceTime(300),
      )
      .subscribe(
        () => console.log(this.fg.value)
      );
  }

  public sendValue() {
    this.inputSubject.next();
  }
}

Working stackblitz

Sivakumar Tadisetti
  • 4,865
  • 7
  • 34
  • 56