0

I am using mat-autocomplte with displayFn & async pipe.

this.genericAutoComplete$ = this.acFormControl.valueChanges.pipe(
                startWith(''),
                debounceTime(400),
                distinctUntilChanged(),
                switchMap(value => {
                    if (value && typeof (value) === "string" && value.length > 2) {
                        return this.searchData(value);
                    } else {
                        return of(null);
                    }
                })
            );

Now my issue is that when i select option from list valueChange will be called & as i am using displayFn value will be object so else block will be executed which returns of(null);

What i want to do is display previously returned/existing list on focus/click of auto-complete.

So list should not get clear when i select option.

I am not sure how to do that. Can anyone point me in the right direction?

Ankur Akvaliya
  • 2,989
  • 4
  • 28
  • 53

1 Answers1

0

Just like you are checking if the value is a string, you can check if the value is an object. If it is, return to search by the object property that you have defined. Here in my demo, that would be the property name:

this.filteredOptions = this.myControl.valueChanges.pipe(
  startWith(''),
  debounceTime(400),
  switchMap(value => {
    if (value && typeof (value) === "string" && value.length > 2) {
      return this.doFilter(value);
    } 
    // add this check:
    if (typeof (value) === "object") {
      // filter by the object property you have, for me it's "name"
      return this.doFilter(value.name);
    }
    // no need for else, if either of above is truthy, this code wont be executed
    return of(null);
  })
);

StackBlitz DEMO

AT82
  • 71,416
  • 24
  • 140
  • 167