rn16 rn16 - 10 months ago 991
TypeScript Question

ng bootstrap 4 - typeahead open on focus

I use ng-bootstrap 4 (beta 8). At the moment i have this:

<ng-template #rt let-r="result" let-t="term">
{{ r.label }}
</ng-template>

<input
id="typeahead-focus"
class="form-control"
[(ngModel)]="model"
[ngbTypeahead]="search"
[inputFormatter]="formatter"
[resultTemplate]="rt"
(focus)="focus$.next($event.target.value)"
(click)="click$.next($event.target.value)"
#instance="ngbTypeahead"
/>


Now, I want to open typeahead, if the user click in the input element. How can I do this?

this.search = (text$) =>
text$
.map(term => (term === '' ? this.items : this.items.filter(v => v.label.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10));

this.formatter = (x: {label: string}) => {
console.log(x);
return x.label;

Answer Source

The following solution works for me:

Add onFocus event to your input search

my.html file

 <input 
    (focus)="onFocus($event)" 
    type="text" 
    (selectItem)="onItemSelected($event)" 
    [(ngModel)]="myModel" 
    [ngbTypeahead]="search" 
    [resultTemplate]="rt" 
    [inputFormatter]="formatter"/>

my.ts file

  public onFocus(e: Event): void {
    e.stopPropagation();
    setTimeout(() => {
      const inputEvent: Event = new Event('input');
      e.target.dispatchEvent(inputEvent);
    }, 0);
  }

  search = (text$: Observable<string>) =>
    text$
      .debounceTime(200)
      .distinctUntilChanged()
      .map(term => this.myList
          .filter(v => this.myfilter(term))
          .slice(0, 10));

Also take a look at Typeahed: allow search on focus #698

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download