Search code examples
angularbootstrap-typeahead

ngbtypeahead filter angular 4


I need to remove previous reults from ngbtypeahead when the user not select one option, but when remove all characters in input text the result still showing

NgbdTypeaheadHttp.component.ts

export class NgbdTypeaheadHttp {
model: any;
searching = false;
searchFailed = false;
clickedItem: string;
constructor(private _service: PeopleService) { }
// Added
formatMatches = (value: IPeople) => value.DisplayName || '';
search = (text$: Observable<string>) =>
    text$
        .debounceTime(300)
        .distinctUntilChanged()
        .do(() => this.searching = true)
        .switchMap(term => term.length < 2 ? []
            : this._service.search(term)
                .do(() => this.searchFailed = false)
                .catch(() => {
                    this.searchFailed = true;
                    return Observable.of([]);
                }))
        .do(() => this.searching = false);


selectedItem(item: People) {
    this.clickedItem = item.Account;
}

How can I clear typeahead results and how can I filter the remote data in Observable function?

Thanks!


Solution

  • In Service send empty observable if empty search term.

    Service function:

    search(search: string): Observable<any> {
        if (search === '') {
            return Observable.of([]);
        } else {
            // other stuff
        }
    }