Angular2 md-autocomplete : How to manage onkeydown?

I implemented Angular2 material autocomplete in my app. And I am now looking for a way to manage the keydown.enter function properly.

Because the click function below works the way I expect, I naturally tried :

<md-input-container>
 <input type="text" placeholder={{appName}} mdInput [formControl]="term" [mdAutocomplete]="auto">
 </md-input-container>
<md-autocomplete #auto="mdAutocomplete" md-focus>
 <md-option *ngFor="let item of items" [value]=item.title (click)="loadData(item)" (keydown.enter)="loadData(item)">              
   <span>{{item.title}}</span>
 </md-option>
</md-autocomplete>

But the function is not triggered. If I move the keydown.enter function in md-input-container, like this :

<md-input-container >
 <input type="text" placeholder={{appName}} mdInput [formControl]="term" [mdAutocomplete]="auto" (keydown.enter)="loadData(item)">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" md-focus>
 <md-option *ngFor="let item of items" [value]=item.title (click)="loadData(item)">              
  <span>{{item.title}}</span>
 </md-option>
</md-autocomplete>

It works, but then I don't have access to my item element anymore...

I am sure there is a simple way around this, but I haven't been able to figure it out. How can I get my item object within md-input-container ?

Here is a Plunker.

Upvotes: 1

Views: 945

Answers (1)

You can get the selected item in md-option by calling (onSelect)="loadData(item)" instead of the 'click' and 'keydown' functions.

Edit : As pointed out by Joshua below, you should now call onSelectionChange event.

Upvotes: 2

Related Questions