在Angular 2 / Material中禁用对话框模式下的自动聚焦

106
我正在使用 Angular Material-2 中的对话框。
问题是:在 iPhone 或平板电脑上打开模态对话框时,我无法禁用自动聚焦。在 iOS 上,它会自动将焦点放在对话框中的第一个输入字段上!
我尝试了使用 tab 索引和其他输入字段的自动聚焦,但它不起作用。
我的代码中使用 Angular 2,在我的对话框中我使用 form-control。我尝试使用 markasuntouched afterviewInit,但仍然存在相同的问题!!
4个回答

224

自从 @angular/material@5.0.0-rc.1 版本开始,MatDialogConfig 中有一个特殊选项 autoFocus

/** Whether the dialog should focus the first focusable element on open. */
autoFocus?: boolean = true;

因此,您可以按以下方式使用它:

let dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
  width: '250px',
  data: { name: this.name, animal: this.animal },
  autoFocus: false   <============================== this line
});

Stackblitz 示例


你能帮我解决这个问题吗?https://dev59.com/ilQK5IYBdhLWcg3wQt1t @yurzui - Zhu
23
此外,使用restoreFocus: false来禁用对话框关闭后的焦点恢复。 - surazzarus
@surazzarus 似乎适用于版本 >= 8。 - Worthy7
在Angular Material中,默认情况下应该禁用自动对焦。他们的示例中没有一个将对话框按钮默认设置为聚焦状态,因此大多数开发人员不应该期望这种行为。 - Glenster
在v14中已经移除了布尔值:14.0.0 Remove boolean option from autoFocus. Use string or AutoFocusTarget instead.请使用字符串或AutoFocusTarget代替。 - Get Off My Lawn

6

我使用了一种解决方案,在打开对话框时禁用自动聚焦,并避免在最后选择的按钮上自动聚焦。我发现这对 Angular Material 中的对话框和底部表单控件都很有效,代码如下:

this.dialog.open(YourComponent, {
      data: inputData,
      width: '100%', 
      autoFocus: false, 
      restoreFocus: false
    });

this.matBottomSheet.open(FilePickerComponent, {
      data: inputData,
      autoFocus: false,
      restoreFocus: false});

2

CDK版本14+

从版本14开始,不再支持布尔值。因此,要使用autoFocus禁用焦点,可以传递一个不存在的查询选择器。

@breaking-change
14.0.0从autoFocus中删除布尔选项。改为使用字符串或AutoFocusTarget。

this.dialog.open(DialogOverviewExampleDialog, {
  autoFocus: '__non_existing_element__'
})

1
实际上,在较新的Mat Design中,现在已经支持autoFocus: false - undefined

0
有点取巧,因为AutoFocusTarget对我没用。
  <button class="generalBtn" [mat-dialog-close]="true" #confirmBtn>{{ data.confirmText }}</button>

然后(从打开模态框的组件获取焦点选项)
  @ViewChild('confirmBtn') confirmBtn: ElementRef;

  ngAfterViewChecked(): void { // using last life cycle before destroy to remove material auto focus
if(this.data.focusOnConfirm) {
  this.confirmBtn.nativeElement.focus();
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接