Set focus on input inside alert prompt


#1

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.


#2

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.


#3

Ok @mhartington.

Thanks for your advice. :wink:


#4

any news?
thank you :slight_smile:


#5

#6

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


#7

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


#8

This works flawlessly