Issue
I have a dialog component that has the posibily to be invoked on every page. The think it is that has a button that needs to be focused, but when closes the dialog I lose the original focus from the page he appeared.
As can see the image this is the representation of what is happening.
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>
The logic of the component:
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();
}
}
Is there something that returns to me where it was his original focus? I was thinking that I can force the reloading of that page but It will not be the best performance for the app
Solution
Can you please try to save the currently focused button element before opening the dialog and then restore the focus state on closing the dialog.
Try this :
Define a variable which will store the activeElement before open the dialog.
focusedElementBeforeDialog: HTMLElement | null = null; . . . ngAfterViewInit() { this.focusedElementBeforeDialog = document.activeElement as HTMLElement }
Now, on dialog close, Set focus back to the element that was focused before the dialog was opened.
closeDialog() { if (this.focusedElementBeforeDialog) { this.focusedElementBeforeDialog.focus(); } this.isVisible = false; }
Answered By - Rohìt Jíndal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.