我有一个对话框组件,可以在每个页面上调用。我认为它有一个需要聚焦的按钮,但是当关闭对话框时,我从他出现的页面中失去了原始焦点。
如图像所示,这是正在发生的事情的表示。
Dialog.component.html:
<div *ngIf="isVisible">
<div class="dialog">
<div class="msgContainer" *ngIf="message" style="color: black;">Message
</div>
<ng-container">
<button #closeDlg class="btnAccept" (click)="closesDlg()" appAutofocus>Close</button>
</ng-container>
</div>
</div>
组件逻辑:
export class DialogComponent implements OnDestroy{
isVisible! = boolean;
private _keySubscription!: Subscription;
private actionSubscription: Subscription;
constructor(
private keysService: KeysService,
private actionService: ActionService,
private router: Router,
private renderer2: Renderer2,
private activatedRoute: ActivatedRoute
){
isVisible = true;
this.closeDialog();
}
closeDialog(): void{
setTimeOut(() => {
this.isVisible = false;
});
}
private initKeyControl(): void {
this._keySubscription = new Subscription();
this.keysService.forwardKeysExceptMedia();
this._keySubscription = this.keysService
.getKeyEventListener(VK_ENTER)
.pipe(
take(1),
switchMap(() => {
console.log('Has been clicked');
this.cerrarDialogoYConfirmar();
return of(null);
})
)
.subscribe();
}
ngOnDestroy(): void {
this.actionSubscription.unsubscribe();
this._keySubscription.unsubscribe();
this.renderer2.destroy();
}
}
有什么东西让我回到了他最初关注的焦点吗?我想我可以强制重新加载该页面,但这不会是应用程序的最佳性能
您能否尝试在打开对话框之前保存当前聚焦的按钮元素,然后在关闭对话框时恢复焦点状态。
试试这个:
定义一个变量,用于在打开对话框之前存储 activeElement。
focusedElementBeforeDialog: HTMLElement | null = null;
.
.
.
ngAfterViewInit() {
this.focusedElementBeforeDialog = document.activeElement as HTMLElement
}
现在,在对话框关闭时,将焦点设置回打开对话框之前聚焦的元素。
closeDialog() {
if (this.focusedElementBeforeDialog) {
this.focusedElementBeforeDialog.focus();
}
this.isVisible = false;
}