【问题标题】:Select the second button in an angular material modal选择角度材料模态中的第二个按钮
【发布时间】:2020-04-26 20:12:26
【问题描述】:

我有一个简单的角度材料模态。我想在打开/加载时关注是按钮。我确实通过在 no 按钮上设置 tabindex='-1' 并在提供程序中设置 autoFocus: true 来实现这一点。但是,这会导致用户体验问题,您无法使用键盘聚焦 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

可选:如何强制焦点停留在我的模态框内直到它关闭?

【问题讨论】:

标签: html angular angular-material-5


【解决方案1】:

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

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

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

【讨论】:

  • 我无法打开 StackBlitz 链接。您能否在答案中提供相关代码?这就是说cdkFocusInitial 似乎工作;)。
  • @RMo cdkFocusInitial 是您设置焦点并保持键盘导航所需的全部内容。不要忘记删除您的其他标签索引。你还有什么我没有提到的吗? (我将编辑以提供示例)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 2020-02-29
  • 2016-10-18
  • 2020-02-06
  • 1970-01-01
  • 2020-09-20
相关资源
最近更新 更多