简体   繁体   English

Mat-select:让它选择第一个mat-option

[英]Mat-select: have it select the first mat-option

I have many angular material selects dropdowns and their respective mat-options are updated in aa reactive way depending on the other values (in other words there is filtering of the options). 我有很多角度材质选择下拉菜单,它们的相应mat-options根据其他值以反应方式进行更新(换句话说,这些选项进行了过滤)。 It can look like that 看起来像

<mat-select #selects (selectionChange)='formChanges()' [placeholder]='element.label' [disabled]='false' required>
  <ng-container *ngFor="let opt of item.options; index as index">
  <mat-option *ngIf="!videoService.filterStore[item.id] || videoService.filterStore[item.id].filter.includes(index)" [value]="opt">
    {{opt.label}}
  </mat-option>
</ng-container>
</mat-select>

I am unhappy with one behaviour: I don't want to have the select unassigned. 我对一种行为不满意:我不想取消选择的分配。 I want them to always pick the first option that passes the filter. 我希望他们始终选择通过过滤器的第一个选项。

You merely need to set the value of the select whenever its list is updated. 只要更新选择列表,您只需要设置选择的值即可。 For example: 例如:

export class SelectExample {

  @ViewChild(MatSelect) select: MatSelect;

  updateSelectOptions() {
    // update the options
    ...

    // update the select value to the first item
    // might need to use a timeout to wait until the select has reloaded the options
    setTimeout(() => this.select.value = this.select.options[0].value);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM