在Angular中,要实现对话框的初始键盘焦点,可以使用Angular Material Dialog模块提供的选项。
首先,在打开对话框时,需要将焦点设置在要让用户聚焦的元素上,可以使用@ViewChild装饰器来获取模板中的DOM元素。
例如,在模板中添加一个按钮作为焦点元素:
然后在组件代码中获取该按钮元素,将焦点设置在它上面:
import { Component, ElementRef, ViewChild, AfterViewInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'dialog-example',
templateUrl: 'dialog-example.html',
})
export class DialogExampleComponent implements AfterViewInit {
@ViewChild('focusEl', { static: false }) focusEl: ElementRef;
constructor(
public dialogRef: MatDialogRef) {}
ngAfterViewInit(): void {
this.focusEl.nativeElement.focus();
}
}
在这个示例中,使用了Angular Material对话框模块提供的MatDialogRef API来处理对话框的行为。
最后,当打开该对话框时,可以设置对话框选项,以便让对话框跳过其它可聚焦元素,直接将焦点设置在按钮元素上:
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { DialogExampleComponent } from './dialog-example.component';
@Component({
selector: 'app-root',
template: '',
})
export class AppComponent {
constructor(private dialog: MatDialog) {}
openDialog(): void {
const dialogRef = this.dialog.open(DialogExampleComponent, {
autoFocus: false,
});
dialogRef.afterClosed().subscribe(() => {