首页 > 解决方案 > 打开 mat-select 对话框时聚焦特定的 mat-option 项?

问题描述

我想在打开 mat-select 时自动关注一个选项(滚动到一个选项)。我认为通过一些搜索可以轻松解决这个问题,但我无法在任何地方找到可靠的答案。

这是我使用的垫选择。

             <mat-select required name="AngabeId" [(ngModel)]="bedingungszielList[0]?.BedingungenList[i].AngabeId">
                <ng-container *ngFor="let antragsbereich of antragsBereichListWithAngabelist">
                  <mat-optgroup *ngIf="antragsbereich.AngabeList.length > 0" [label]="antragsbereich.Bezeichnung" class="bedigungOptGroup">
                    <ng-container *ngFor="let angabe of antragsbereich.AngabeList">
                      <mat-option *ngIf="angabe.Id !== Id" [value]="angabe.Id" class="bedigungOptions">
                        {{ angabe.Fragetext }}
                      </mat-option>
                    </ng-container>
                  </mat-optgroup>
                </ng-container>
              </mat-select>

这是我想要实现的一些示例代码,angabe.Id 是 mat-option ngmodel。

  this.antragsBereichListWithAngabelist.forEach(element => {
    element.AngabeList.forEach(angabe => {
       if(angabe.Id===962)
         angabe.Id.focus(); // mat-option focus, my intention, sample code(bad)
    });
  });

这是带有图像的示例: mat-option focus

标签: htmlangulartypescriptangular-materialselect-options

解决方案


如果我理解您的问题,您希望在打开选择框时关注一个选项。所以,我建议你在 mat-select 中使用(打开的)事件。这是我尝试过的:

.html

<mat-form-field>
  <mat-label>Cars</mat-label>
  <mat-select [(ngModel)]="default" required (opened)="selectOpened()">
    <mat-option value="volvo">Volvo</mat-option>
    <mat-option value="saab">Saab</mat-option>
    <mat-option value="mercedes">Mercedes</mat-option>
    <mat-option value="audi">Audi</mat-option>
  </mat-select>
</mat-form-field>

.ts

default = '';

selectOpened() {
    this.default = 'audi';
}

打开选择框时,此代码将聚焦奥迪选项。希望这对你有用。


推荐阅读