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 ?
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>
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';
// ...
onSelectionChanged(event: MatAutocompleteSelectedEvent) {
console.log(event.option.value);
}
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.
The onSelectionChange
event replaced the selected
event. Now it's possible to recognize when the item is selected or deselected.
It's needed to pass an $event
parameter to the target method to differentiate between the two cases, otherwise md-autocomplete will invoke the method twice (once with the new selected item and once with the deselected/previous value).
It would be nice though if the documentation would be a bit more clear about these changes.
Below how to get only the "on select" event:
Template
<md-autocomplete #panel="mdAutocomplete" [displayWith]="displayFn">
<md-option (onSelectionChange)="selected($event, country)"
*ngFor="let country of filteredCountries | async" [value]="country">
<div class="selector-elements">
{{ country.name }}
</div>
</md-option>
Controller
selected(event: MdOptionSelectionChange, country: ICountry) {
if (event.source.selected) {
this.propagateChange(country);
}
}
来源:https://stackoverflow.com/questions/42427928/material-2-autocomplete-select-option