在打开模态框的时候,使用Angular自带的ViewChild装饰器获取模态框的DOM元素,然后手动触发该元素的focus事件,即可使模态框获取焦点。
示例代码如下:
HTML模板文件:
组件文件:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({ // ... }) export class MyComponent { @ViewChild('modal', { static: false }) modalEl: ElementRef;
openModal() { // 打开模态框 // ...
// 手动触发模态框元素的focus事件
this.modalEl.nativeElement.focus();
} }