【问题标题】:How to autofocus by default on dialog button from Menu Icon in Angular Material?默认情况下,如何在 Angular Material 中的菜单图标对话框按钮上自动对焦?
【发布时间】:2023-03-18 08:55:01
【问题描述】:

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

从菜单中选择任何菜单项后,最初的焦点会停留在 菜单图标上。我想默认转移 focus on dialog button 以便在 Enter-Key hit 时,在执行所需操作后关闭对话框。 请在此处查看演示Stackblitz

【问题讨论】:

  • 您应该重新创建您在堆栈闪电战中遇到的问题。据我所知,关注材料日期选择器并按 Enter 不会将焦点转移到下一个元素
  • 嗨 bryan60,我已经添加了演示链接,您可以查看一下吗?

标签: angular-material modal-dialog menuitem enter autofocus


【解决方案1】:

我解决了这个问题,因为每当我尝试单击“从菜单中删除”时,Spinner 都会阻止焦点移动到对话框按钮中。 我在 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 方法中添加 timeout,如下所示。

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();
          }); 
      });
  }

【讨论】:

    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 2015-06-14
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    相关资源
    最近更新 更多