material 2 Autocomplete: select option

The Material Autocomplete component has its own optionSelected event output:

Template:

<mat-autocomplete (optionSelected)="onSelectionChanged($event)"> 
  <mat-option *ngFor="let item of myItems" [value]="item">
    {{ item }}
  </mat-option>
</mat-autocomplete>

Controller:

import { MatAutocompleteSelectedEvent } from '@angular/material/autocomplete';

// ...

onSelectionChanged(event: MatAutocompleteSelectedEvent) {
  console.log(event.option.value);
}

See: Angular Material API Docs - MatAutocompleteSelectedEvent


I couldn't get the answer "onSelect" going with the latest angular material (2.0.0-beta.3). It was never called.

I'm finding now that it is:

  <md-option *ngFor="let item of item" [value]="item.name" (onSelectionChange)="myChangeFunc($event, item)">
    {{ item.name }}
  </md-option>

In other words it seems to be called onSelectionChange now. The docs still seem vague and continue to say "Stream of autocomplete option selections" which doesn't really mean anything.

See Franceso's answer also, however for most situations you will need to pass in $event to check the event information.


On md-option you can set "onSelect"

<md-autocomplete #auto="mdAutocomplete">
    <md-option (onSelect)="callSomeFunction()" *ngFor="let state of states" [value]="state.name">{{ state.name }}</md-option>
</md-autocomplete>

Since beta 3, functionality has changed:

<md-autocomplete #auto="mdAutocomplete">
    <md-option (onSelectionChange)="callSomeFunction()" *ngFor="let state of states" [value]="state.name">{{ state.name }}</md-option>
</md-autocomplete>