Search code examples
twitter-bootstrapangularng2-bootstrap

Typehead in ng2-bootstrap cannot show items in Angular 2


UPDATED: It supports now nested property now. https://github.com/valor-software/ng2-bootstrap/issues/135


I am using ng2-bootstrap in Angular 2.

I am trying to use Typeahead.

The example code

private statesComplex:Array<any> = [
    {id: 1, name: 'Alabama'}, {id: 2, name: 'Alaska'}, {id: 3, name: 'Arizona'}];

and

<input [(ngModel)]="selected"
       [typeahead]="statesComplex"
       (typeaheadOnSelect)="typeaheadOnSelect($event)"
       [typeaheadOptionField]="'name'"
       class="form-control">

runs well.

But when I try to change the data format

private statesComplex:Array<any> = [
    {id: 1, profile: {name: 'Alabama', email: '111'}}, {id: 2, profile: {name: 'Alaska', email: '222'}}, {id: 3, profile: {name: 'Arizona', email: '333'}}];

and use

<input [(ngModel)]="selected"
       [typeahead]="statesComplex"
       (typeaheadOnSelect)="typeaheadOnSelect($event)"
       [typeaheadOptionField]="'profile.name'"
       class="form-control">

It does not work. I think the problem is related with typeaheadOptionField, but I don't know how to write it.

Thanks


Solution

  • Looks like this kind of notation is not going to be recognised as nested property of sub-object (see source). In this case, you could preprocess data a little bit. Maybe by actually introducing this helper property:

    this.statesComplex.forEach(state => state['profile.name'] = state.profile.name);
    

    It will add new profile.name property to all objects so typeahead should work as expected.