当焦点放在 Mat-Select 上时,在 Angular 中打开 Mat-Select 下拉菜单

Kru*_*hah 5 angular-material angular

如果来自前一个字段或 Shift + Tab 如果来自下拉后的下一个字段,我想在按下 Tab 键时打开 Mat-Select 下拉菜单。如何实现这一目标?

这是我的帐户页面

现在,如图所示 - 帐户类型是我的 Mat-Select 下拉菜单。因此,如果我从帐户名称按 Tab 键,焦点将转移到帐户类型,但我想打开下拉菜单。就像 Wise 一样,如果我按公司的 Shift + Tab 组合键,我想打开“帐户类型”下拉菜单。

我经历了所有Angular Material Select API,但无法实现我的目标。

这是我的帐户类型下拉代码 -

<div class="row">
    <div class="col-lg-4 col-md-4 col-sm-12 col-label-line-height">
        <mat-label>Account Type </mat-label>
    </div>
    <div class="col-lg-8 col-md-8 col-sm-12">
        <mat-form-field>
            <mat-select formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过 -

<div class="row">
    <div class="col-lg-4 col-md-4 col-sm-12 col-label-line-height">
        <mat-label>Account Type </mat-label>
    </div>
    <div class="col-lg-8 col-md-8 col-sm-12">
        <mat-form-field>
            <mat-select (open)="matSelectOpen($event)" formControlName="AccountTypeCode" [disabled]="this.DataService.LeaseCount" [(ngModel)]="AccountModel.AccountTypeCode">
                <mat-option *ngFor="let AccountType of this.AccountTypeList" [value]="AccountType.Code">
                {{ AccountType.Name }}
                </mat-option>
            </mat-select>
            <mat-error *ngIf="hasError('AccountTypeCode', 'required')">Account Type is required</mat-error>
            <mat-error *ngIf="hasError('CompanyCode', 'min')">Account Type is required</mat-error>
        </mat-form-field>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

在 .ts 文件中 -

matSelectOpen(e) {
    Console.log(e); //just to check whether function is called or not
}
Run Code Online (Sandbox Code Playgroud)

我也尝试过如下事件:-

(触发器)="matSelectOpen($event)"

(panelOpen)="matSelectOpen($event)"

任何帮助,将不胜感激。

Eld*_*dar 6

尝试这个

 <mat-select #accType (focus)="accType.open()">
Run Code Online (Sandbox Code Playgroud)

这意味着给您选择的模板引用。然后在焦点上打开它。

编辑 :

自从我回答这个问题已经有一段时间了,并没有注意到@KrunalShah 发表的评论。

如果你想要一个可以应用于多个选择的通用解决方案,你是对的,给templateRef每个选择元素都是不可行的。在这里你可以做的是创建一个angular directive服务于这个目的:

@Directive({
  selector: "mat-select[appOpenOnFocus]"
})
export class OpenOnFocusDirective {
  constructor(select: MatSelect) {
    const nativeEl = select._elementRef.nativeElement;
    nativeEl.addEventListener("focus", () => {
      select.open();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

然后mat-select像这样使用它:<mat-select appOpenOnFocus>

闪电战