Return empty array if filter triggers in rxjs stream

71 Views Asked by At

I have an autocomplete input field, which reacts to user input and executes a search function. I have a filter set up in order to only start searching if the input-value has more than two characters. Since I am showing the options$ in an *ngFor loop, I would like to return an empty array if the filter triggers, so the dropdown does not show any results.

This works fine if a user starts typing, but if they delete the whole input the results of the last search stays visible.

So basically what I would like to do is return an empty array, if the filter statement triggers.

public control = new FormControl()

this.options$ = this.control.valueChanges.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  filter((val) => val.length > 2),
  switchMap((search) => this.filterFunc<T>(search))
);

I tried to introduce another boolean, which could handle the open and closed state of the dropdown, but I thought there must be a way to this without setting values imperatively.

1

There are 1 best solutions below

1
Ali Ataf On BEST ANSWER

You don't actually wants to filter because filter will prevent the stream from emitting a value at all if the length is less than 2, but you do want to do something in that case (return an empty array) and not actually filter it.

So you can remove the filter and handle the case in switchMap itself:

public control = new FormControl()

this.options$ = this.control.valueChanges.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap((search) => search.length > 2 ? this.filterFunc<T>(search) : of([]))
);