I am currently working on developing a typeahead feature that triggers a service call on keyup event as the user types in an input field. The challenge I face is that my input field is enclosed within an *ngIf block, which requires me to utilize ViewChildren and subscribe to its changes to access the input element. However, the method being called does not return any value, making it difficult for me to correctly structure rxjs operators for this task.
Below is my existing implementation:
private searchBoxPlaceholder: ElementRef;
@ViewChildren("searchbox", { read: ElementRef }) elementRefs: QueryList<ElementRef>;
public ngAfterViewInit(): any {
this.elementRefs.changes.subscribe(() => {
if (this.elementRefs.toArray().length) {
fromEvent(this.elementRefs.first.nativeElement, "keyup")
.pipe(
filter(Boolean),
debounceTime(2000),
distinctUntilChanged(),
tap(() => {
this.filterSearch(this.elementRefs.first.nativeElement.value);
})
)
.subscribe();
}
});
}
Although this solution works, I believe there might be a more efficient way to organize this code without nesting multiple subscribes. Additionally, I am uncertain whether tap() is the most suitable rxjs operator for this scenario. I have experimented with switchMap, mergeMap, and concatMap variations, but due to filterSearch not returning an Observable, I have not been successful in achieving the desired outcome.