简体   繁体   中英

ngx-bootstrap Custom typeahead not working

I'm trying to create a custom typeahead that searches my API every time the user types something but its not working. Its not even entering the autocomplete() function. I'm using Angular 4 CLI (1.4.2), bootstrap 4, and ngx-bootstrap (1.9.3). What am I doing wrong?

component.ts

public autoCompleteRef = this.autoComplete.bind(this);

public autoComplete() {
    let searchParams = new URLSearchParams();
    searchParams.set('search', this.autoCompleteSearchTerm);

    return this.http.get(this.api_url, {search: searchParams, headers: headers})
        .map(res => res.json())
        .map((el)=> {
            return el.map((data)=> {
                return ({id: data.id, name: data.name});
            });
        })
        .toPromise();
}

public typeaheadOnSelect(e): void {
    console.log('Selected value: ', e.value);
}

html

<input class="form-control"
       [(ngModel)]="autoCompleteSearchTerm"
       [typeahead]="autoCompleteRef"
       [typeaheadOptionField]="'name'"
       [typeaheadWaitMs]="300"
       [typeaheadMinLength]="1"
       (typeaheadOnSelect)="typeaheadOnSelect($event)">

Call that function with (keyup). That will do the trick.
And whenever the user types a character, it will call the API and store the result in a variable, that variable will be passed as [typeahead]="autoCompleteRef" .

Call the function something like:

<input class="form-control"
       [(ngModel)]="autoCompleteSearchTerm"
       [typeahead]="autoCompleteRef"
       [typeaheadOptionField]="'name'"
       [typeaheadWaitMs]="300"
       [typeaheadMinLength]="1"
       (keyup)="typeaheadOnSelect($event)">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM