How do I set the focus on the LoginForm component to the Username field?
There’s no API for that, but this seems to work:
UI.getCurrent().getPage().executeJavaScript("document.getElementById(\"vaadinLoginUsername\").focus();");
Thank you Olli!
It works as expected.
I made a ticket here as well: https://github.com/vaadin/vaadin-login-flow/issues/53
Hi,
I’m not sure, but I think you can get the UserNameField from the LoginForm, get its element and set the focus.
Not directly from Java code as far as I can tell.
Will open this old thread again because I’ve spent few hours on it and nothing worked for me, so it’ll maybe help someone. Doesn’t matter where I was trying to add js, it was always invoked before login page is attached to DOM, so wasn’t able to set focus. (Vaadin 16)
I also tried to add
window.addEventListener('DOMContentLoaded', function(){});
but it also didn’t work. For some reason callback is not fired.
What worked for me is kinda hack with MutationObserver:
@PageTitle("Login")
@Route("login")
class LoginView(): VerticalLayout(),
BeforeEnterObserver {
override fun beforeEnter(event: BeforeEnterEvent) {
event.ui.page.executeJs(loginPageFocusHack())
}
private fun loginPageFocusHack(): String {
return """
debugger;
const observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.target.id === "outlet") {
document.getElementById("vaadinLoginUsername").focus();
observer.disconnect();
}
});
});
observer.observe(document.body, {
childList: true
, subtree: true
, attributes: false
, characterData: false
});
""".trimIndent()
}
}