默认情况下,如何在Angular Material中的“菜单”图标上的对话框按钮上自动对焦?

问题描述

我在菜单图标下有两个菜单删除创建。我要从菜单图标中选择任何操作,该操作会打开带有两个按钮 Delete Cancel 的确认对话框。

菜单中选择任何菜单项后,

最初的焦点停留在菜单图标上。我想认将焦点在对话框按钮上移,以便在按 Enter-Key 命中时,它在执行所需的操作后关闭对话框。 请在Stackblitz

上查看演示

解决方法

我解决了此问题,因为当我尝试单击“从菜单中删除”时,微调器阻止焦点移至对话框按钮。 我在HTML中添加了id="deletebutton",如下所示。

<div *ngIf="!loadspinner">  
<mat-dialog-content>
    <p>Are you sure to delete this?</p>
  </mat-dialog-content>
  <mat-dialog-actions align="center">
    <button id="deletebutton" mat-raised-button color="primary" (click)="deleteDocument()">Delete</button>
    <button mat-raised-button mat-dialog-close tabindex="-1" (click)="close()" style="border-color:#3f51b5;">Cancel</button>
  </mat-dialog-actions>
  </div>

并在.ts文件的ngOnInit方法中添加了超时,如下所示。

ngOnInit() {
      this.service.validate(this.data).subscribe(value => {
        this.loadspinner = false;
          if (value != null) {
             this.warningMsg = value.statusMessage; 
          } else {
            this.warningMsg = "";
          } 
        //For autoFocus in dialog button as Spinner prevents it to set by deafault
          setTimeout(()=>{
            document.getElementById('deletebutton').focus();
          }); 
      });
  }