I've created an Angular directive which is applied to an input and emits its values with some delay (for search).
The code of this is following
@Directive({
selector: '[search-field]'
})
export class SearchFieldDirective {
@Input() searchFieldValueOutputDelay = 400;
private _inputObservable$ = new Subject();
@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
debounceTime(this.searchFieldValueOutputDelay),
distinctUntilChanged(),
tap(() => console.log('emit', this.searchFieldValueOutputDelay))
);
@HostListener('keyup', ['$event.target.value'])
onChange(e) {
console.log("change");
this._inputObservable$.next(e);
}
}
The problem is that searchFieldValueOutputDelay
is taken only first time and therefore it has value of 400 and not the value I've provided on input.
<input (searchValueUpdated)="searchCard($event)" [searchFieldValueOutputDelay]="1000" type="search">
The value for debounceTime is only evaluated once, on observable creation time.
To be able to dynamically update debounceTime, use debounce together with timer, like this :
@Output() searchValueUpdated = this._inputObservable$.asObservable().pipe(
debounce(()=>timer(this.searchFieldValueOutputDelay)),
distinctUntilChanged(),
tap(() => console.log('emit', this.searchFieldValueOutputDelay))
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With