I am using mat-select
, and my requirement is to revert back the selection for a specific value of mat-select
's mat-option
.
For example, Have a look at this stackblitz
Here mat-select
has three options; when I select Canada
, it should revert back to the value I've selected previously.
onCountryChange($event) {
const oldIndex = this.countries.indexOf(this.selectedCountry);
if ($event.value.short === 'CA') {
this.selectedCountry = this.countries[oldIndex];
} else {
this.selectedCountry = $event.value;
}
}
I can see that the value is getting updated from the json
besides the mat-select
. However, the mat-select
is not updating the selected option.
So far I tried setting value using FormControl
, setTimeout
, by attaching just short
property of the object instead of attaching entire object with mat-option
(this stackblitz for reference). But couldn't make it work.
I think you should use mat-select-trigger. This is a due to the mat-select using OnPush change detection. You may be interested in using mat-select-trigger. Try that and let me know if it works for you.
<mat-select name="countryVaraible" [value]="selectedCountry" placeholder="Country" (selectionChange)="onCountryChange($event)">
<mat-select-trigger>{{selectedCountry.full}}</mat-select-trigger>
<mat-option *ngFor="let country of countries" [value]="country">
{{country.full}}
</mat-option>
</mat-select>