【问题标题】:How to revert back Mat-Select's selected value for a specific option?如何恢复 Mat-Select 为特定选项选择的值?
【发布时间】:2021-01-14 23:11:06
【问题描述】:

我正在使用mat-select,我的要求是还原选择以获取mat-selectmat-option 的特定值。

例如,看看这个stackblitz

这里mat-select有三个选项;当我选择Canada 时,它应该恢复到我之前选择的值。

  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 并未更新所选选项。

到目前为止,我尝试使用FormControlsetTimeout 设置值,方法是仅附加对象的short 属性,而不是使用mat-option 附加整个对象(this stackblitz 供参考)。但无法让它工作。

【问题讨论】:

    标签: angular typescript angular-material dropdown


    【解决方案1】:

    我认为你应该使用 ma​​t-select-trigger。 这是由于 mat-select 使用 OnPush 更改检测。您可能对使用 ma​​t-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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      • 2022-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多