如何恢复 Mat-Select 为特定选项选择的值?
How to revert back Mat-Select's selected value for a specific option?
我正在使用 mat-select
,我的要求是针对 mat-select
的 mat-option
.[=26= 的特定值恢复 selection ]
例如,看看这个stackblitz
这里mat-select
有3个选项;当我 select Canada
时,它应该恢复到我之前 select 编辑的值。
onCountryChange($event) {
const oldIndex = this.countries.indexOf(this.selectedCountry);
if ($event.value.short === 'CA') {
this.selectedCountry = this.countries[oldIndex];
} else {
this.selectedCountry = $event.value;
}
}
我可以看到除了 mat-select
之外,json
的值也在更新。但是,mat-select
没有更新 selected 选项。
到目前为止,我尝试使用 FormControl
、setTimeout
设置值,方法是仅附加对象的 short
属性,而不是使用 [=14= 附加整个对象](this stackblitz供参考)。但是无法让它工作。
我认为你应该使用 mat-select-trigger。
这是由于 mat-select 使用 OnPush 变化检测。您可能对使用 mat-select-trigger 感兴趣。试试看,让我知道它是否适合你。
<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>
我正在使用 mat-select
,我的要求是针对 mat-select
的 mat-option
.[=26= 的特定值恢复 selection ]
例如,看看这个stackblitz
这里mat-select
有3个选项;当我 select Canada
时,它应该恢复到我之前 select 编辑的值。
onCountryChange($event) {
const oldIndex = this.countries.indexOf(this.selectedCountry);
if ($event.value.short === 'CA') {
this.selectedCountry = this.countries[oldIndex];
} else {
this.selectedCountry = $event.value;
}
}
我可以看到除了 mat-select
之外,json
的值也在更新。但是,mat-select
没有更新 selected 选项。
到目前为止,我尝试使用 FormControl
、setTimeout
设置值,方法是仅附加对象的 short
属性,而不是使用 [=14= 附加整个对象](this stackblitz供参考)。但是无法让它工作。
我认为你应该使用 mat-select-trigger。 这是由于 mat-select 使用 OnPush 变化检测。您可能对使用 mat-select-trigger 感兴趣。试试看,让我知道它是否适合你。
<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>