Topic: How to autofocus an input field after modal popup
Bakke premium asked 11 months ago
Expected behavior Input autofocuses cursor after modal finishes animating into view.
Actual behavior Input receives autofocus while the modal is moving, but disappears after modal stops moving.
I have applied the autofocus property to the input like I do on other forms that I need autofocus-on-load and those work as expected, however there seems to be some sort of view/content refresh after the modal finishes moving into position that is overriding the autofocus that I have applied in the AfterViewInit lifecycle hook, shown here:
ngAfterViewInit(): void {
// Autofocus the dealer code field upon page load.
this.focusDealerCode();
}
focusDealerCode() {
this.dealerCodeField.nativeElement.focus();
}
I can see the field gain the focus as the modal moves down, so I know the above code is being called when the modal is created, but I am unsure how to re-focus on the input after the modal "refreshes" the view when it has moved into position. Is there another lifecycle hook I should be hooking into that is different for modals vs a normal web page component?
Arkadiusz Idzikowski staff answered 11 months ago
As a workaround you can try to use a setTimeout
function that will focus the input after 351ms (after this time, the modal should be fully rendered).
ngOnInit(): void {
setTimeout(() => {
// focus input
}, 351);
}
We will take a closer look at this problem and see what we can do to make it easier to change the element that will be focused on modal init.
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Premium
- Premium support: Yes
- Technology: MDB Angular
- MDB Version: MDB5 5.2.0
- Device: any
- Browser: any
- OS: any
- Provided sample code: No
- Provided link: No