Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 ngbTypeahead filter of list of JSON objects

I've got a ngbTypeahead which when typing in the field should be able to query a list of objects. The formate of the objects in the list "projections" is

{
    code: "6326"
    group: "world"
    name: "WGS 1984"
}

HTML :

<input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="item.outputProjection.name" [ngbTypeahead]="search" />

search filter code in component.ts class :

    search = (text$: Observable < string > ) =>
    text$.pipe(
        debounceTime(200),
        distinctUntilChanged(),
        merge(this.focus$),
        map(term => (term === '' ? this.projections :
            this.projections.filter(v => v.name.toLowerCase().indexOf(term.toLowerCase()) > -1)).slice(0, 10))
    )

When I type into the typeahead what I get is :

enter image description here

But what I would like to show up is the name in the json object.....

Also as a sidenote the folks at bootstrap closed this and said it's not a bug but a feature request:

https://github.com/valor-software/ngx-bootstrap/issues/749

Most modern UI Controls work with objects regardless of platform.

like image 984
yamamoto585 Avatar asked Jun 06 '18 21:06

yamamoto585


2 Answers

Add formatter to your code

formatter = (result: string) => result.name;

also, include formatter to the template.

<input id="typeahead-format" type="text" class="form-control" [(ngModel)]="model" [ngbTypeahead]="search" [resultFormatter]="formatter" />
like image 61
shajan Avatar answered Sep 17 '22 15:09

shajan


Please add formatter and as you are using object as data source for that you need to descontruct your object to get desired fields:

formatter = (x: {name: string}) => x.name;

HTML input element need one more attribute [inputFormatter]

<input id="typeahead-basic" type="text" class="form-control" [(ngModel)]="item.outputProjection.name" [ngbTypeahead]="search" [inputFormatter]="formatter" />
like image 22
Salman Zahid Avatar answered Sep 20 '22 15:09

Salman Zahid