material 2 Autocomplete: select option

Yoamb picture Yoamb · Feb 24, 2017 · Viewed 57.5k times · Source

I want to call a function when an option is selected. After some search it seem that i have to use :

property optionSelections of MdAutocompleteTrigger

In the documentation : https://material.angular.io/components/component/autocomplete optionSelections Stream of autocomplete option selections.

I dont understand that , what is a stream, how to implement this ?

Answer

Martin Schneider picture Martin Schneider · Feb 4, 2018

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