This works fine and, when running on browser, name input is focused automatically. But, when I run my APP on a real device (iPad), autofocus doesn’t work.
Anyone knows how can I focus the first input in my alerts?
This is something we had actually attempted to do some time ago. But as it turns out, setting focus reliably across browsers and OS’s is a much tougher problem then expected.
I honestly would try to avoid it, as it can be a rabbit hole of issues.
Due to the fact, that querySelector(); allways takes the first result, it will focus the first input element, which was found inside the presented alert.
If You want to focus the second, third, etc. You should change querySelector('ion-alert input'); to querySelectorAll('ion-alert input')[2], 2 as a placeholder for the third input element.
Of course you can adapt this to the native components of Angular2(+) like ViewChild and so on. This is just a simplified example.
BTW: You should do that only if You have input elements in Your alert popup, otherwise it will throw errors, because no input element could be found.
Inspired by the above answer, you can make “sure” to pick the correct input field by assigning a unique ID to the input field, making it easier to traverse the entire DOM looking for it. This way, any wrapping divs, ionic updates will affect less:
const alert = (await this.alertController.create({
…
inputs: [
{
id: 'userInput', // or add some super fancy unique name
…
and the
alert.present().then(() => {
// try to autofocus
const firstInput: any = document.getElementById('userInput');
if (firstInput?.focus) {
firstInput.focus();
}