How to display using [displayWith] in AutoComplete Material2 How to display using [displayWith] in AutoComplete Material2 typescript typescript

How to display using [displayWith] in AutoComplete Material2


If you want the entire object to be binded with md-options, then you should bind to option with state and return state.name at displayFn and this way you don't have to bind this.

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">  <md-option *ngFor="let state of filteredStates | async" [value]="state">    {{ state.name }}  </md-option></md-autocomplete>displayFn(state) {  return state.name;}

demo plunker.


and if you want to bind only state.id to md-options, you have to loop through states to find state.name based on state.id and this way binding this is needed.

<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">  <md-option *ngFor="let state of filteredStates | async" [value]="state.id">    {{ state.name }}  </md-option></md-autocomplete>displayFn(id) {  if (!id) return '';  let index = this.states.findIndex(state => state.id === id);  return this.states[index].name;}

demo plunker.