Select angular material 模式中的第二个按钮

Select the second button in an angular material modal

我在 angular material 中有一个简单的模态框。我想在打开/加载时关注是按钮。我确实通过在 no 按钮上设置 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

可选:我如何强制焦点留在我的模式中直到它关闭?

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

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

[编辑 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>