Angular material auto-complete displayWith @Input

Angular Material 2 have awesome components that are really easy to use. Except one the auto-complete. This one is a little brain teaser. Although the documentation provides examples, it is not always really straight-forward how to use designed API. For example the displayWith @Input.

Screen Shot 2017-07-12 at 20.27.44

Let’s say you want to display state code instead of full name as is in above picture.

If you want to parse displayed value from some kind of list or ask your service you have to bind the “right” this. And you have two options, you can either use arrow function, or the bind() function. In this example I will use bind();

<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="parseHash.bind(this)">
<md-option *ngFor="let state of filteredStates | async" [value]="state">
{{ state }}
</md-option>
</md-autocomplete>

So now you have access to the component this from the parseHash() function.

@Component({
selector: 'auto-complete',
templateUrl: 'auto-complete.template.html',
})
export class AutocompleteExample {
...
parseHash(val: string) {
return this.statesHash[val];
}
}

Here is the plunker with example taken from material2 documentation.

Buy me a coffeeOut of coffee 😱, please help!