选择角度材料模态中的第二个按钮

时间:2020-04-26 20:12:26

标签: html angular angular-material-5

我在棱角材料上有一个简单的模态。我想在打开/加载它时关注“是”按钮。我确实通过在无按钮上设置tabindex='-1'并在提供程序中设置了autoFocus: true来实现这一点。但是,这会导致UX问题,使您无法将no按钮对准键盘。如何保持第二个按钮的焦点,同时又可以通过键盘对其进行访问。我还尝试使用tabindex,它似乎不会影响选择。我正在寻找一种优雅的解决方案(最好不要编写打字稿来解决它)

dialog.component.html

<h2 mat-dialog-title>Cookie request</h2>
<mat-dialog-content>Should we use a cookie to automatically log you in next time?</mat-dialog-content>
<mat-dialog-actions>
  <button mat-button [mat-dialog-close]='false' tabindex='-1'>No</button>
  <button mat-button [mat-dialog-close]="true"  tabindex='1'>Yes</button>
</mat-dialog-actions>

摘自app.module.ts

@NgModule({
  declarations: [...stuff],
  imports: [...stuff],
  providers: [
    {provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: {hasBackdrop: true, disableClose: true, autoFocus: true }}
  ],
  entryComponents: [
    DialogComponent
  ],
  bootstrap: [AppComponent]
})

官方文档:https://material.angular.io/components/dialog/api

可选:如何强制焦点保持在模态内部直至关闭?

1 个答案:

答案 0 :(得分:3)

根据Stackblitz of material dialog,您可以看到他们正在使用cdkFocusInitialfocus the OK button

[编辑:可能不准确,但仍然很有趣!]要导航到其他可聚焦元素(如果需要),tabindex似乎无法正常工作,但我认为您的答案在这里:{{ 3}}

[编辑2]::由于某些人无法正确访问stackblitz,因此此处是对话框html代码的示例:

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite animal?</p>
  <mat-form-field>
    <mat-label>Favorite Animal</mat-label>
    <input matInput [(ngModel)]="data.animal">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
</div>