Set focus on input inside alert prompt

Hi everyone,

I show an alert prompt like this:

let alert = Alert.create({
    title: 'Title',
    inputs: [
      {
        name: 'name',
        placeholder: 'Your name here'
      }
    ],
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        handler: data => {
          console.log('Cancel clicked');
        }
      },
      {
        text: 'Save',
        handler: data => {
          console.log('Cancel clicked');              
        }
      }
    ]
  });
  this.nav.present(alert);

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?

I try it with this directive with no luck:

import {Directive, ElementRef, Renderer} from 'angular2/core';

@Directive({
    selector: '.autofocus'
})
export class Autofocus {
    constructor(el: ElementRef, renderer: Renderer) {        
        renderer.invokeElementMethod(el, 'focus', []);
    }
}

Thanks.

1 Like

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.

2 Likes

Ok @mhartington.

Thanks for your advice. :wink:

any news?
thank you :slight_smile:

How to create the reference, when my alert prompt is generated in my .ts file like:

 inputs: [
                {
                    name: 'maschineName',
                    placeholder: 'Name der Maschine',
                    value: maschine.name,

                },

or is there meanwhile any better way to do this?

Thank you

I’ve found a simple solution ( / workaround) for this case.

alert.present(); returns a Promise. So we can simply add the following lines to achieve the expected behaviour:

alert.present().then(() => {
	const firstInput: any = document.querySelector('ion-alert input');
	firstInput.focus();
	return;
});

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.

Cheers
Unkn0wn0x

19 Likes

This works flawlessly

thank u bro :smiley:

Not working on iOS 13 device

you made my day bro.

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();
        }

Works in ionic 7.7.0 on web at least