Why is onSelectionChange called twice?
material has optionSelected event you can use it
<mat-autocomplete #autocomplete="matAutocomplete" (optionSelected)="onSelectionChanged($event)" [displayWith]="displayFn" autoActiveFirstOption>
<mat-option *ngFor="let option of filteredOptions$ | async" [value]="option" >
{{displayFn(option)}}
</mat-option>
</mat-autocomplete>
and get your value that way
onSelectionChanged(event) {
console.log(event.option.value);
}
I was facing the same problem for a mat-option inside a mat-select and fixed this way:
Template
<mat-select>
<mat-option (onSelectionChange)="handleMetaSignalChange(metaSignal.name,$event);" *ngFor="let metaSignal of metaSignals" [value]="metaSignal">
{{ metaSignal.name }}
</mat-option>
</mat-select>
Code
handleMetaSignalChange(metaSignal: string, event: any) {
if (event.isUserInput) { // ignore on deselection of the previous option
console.log('Meta Signal Changed to ' + metaSignal + event.isUserInput);
}
}
If you need to get the whole OBJECT and use its children values in the component:
1- Send both object and $event from DOM to component.ts.
<!-- Printing out the country name and flag only -->
<mat-autocomplete #auto="matAutocomplete">
<mat-option
*ngFor="let country of filteredCountries$ | async"
[value]="country.name"
(onSelectionChange)="getSelectedCountry(country, $event)">
<img class="example-option-img" aria-hidden [src]="country.flag" height="25">
<span>{{country.name}}</span>
</mat-option>
</mat-autocomplete>
2- Now update your values in the component.ts
getSelectedCountry(country: ICountry, event: any): void {
if (event.isUserInput) { // ignore on deselection of the previous option
console.log("Selected country name: ", country.name);
console.log("Selected country code: ", country.code);
console.log("Selected country flag link: ", country.flag);
}
Note: ICountry is my country Interface which is not required to have.