import { Directive, Renderer, ElementRef} from '@angular/core';
@Directive({
selector: '[focuser]' // Attribute selector
})
export class Focuser {
constructor(private renderer:Renderer,
private elementRef:ElementRef) {
}
ngAfterViewInit() {
// we need to delay our call in order to work with ionic ...
setTimeout(() => {
const element = this.elementRef.nativeElement.querySelector('input');
this.renderer.invokeElementMethod(element, 'focus', []);
}, 1000);
}
}
Hey Blaydator,
I am having the same issue here and couldn’t make input field focus on iPhone (Keyboard doesn’t appear too). Do you have a solution on this?
Mine is a little different.
On ios 10,
Using the old webkit
preference name=“CordovaWebViewEngine” value=“CDVUIWebViewEngine”
Trying to do a wizard in a modal. After a couple of screens we have a form for the users address. What is strange on iphone 7 with ios 10 the zip code (last value in the from) is what gets focused.
How can I change that to get focus on the first input?
Use ngAfterViewChecked() Angular hook and execute .setFocus() inside it.
While working with the Ionic 3 Framework I came across (as it turns out) popular problem of autofocusing an input after showing a component on the page.
The most popular answer to this problem advises to use setTimeout
I hate such workarounds so I’ve decided to dig deeper. While none of the available Ionic lifecycle hooks works, in that case, there are also Angular lifecycle hooks. It turns out that ngAfterViewChecked is the one I was looking for:
ngAfterViewChecked() {
this.myInput.setFocus()
}
So that is clean setFocus() solution for Ionic without using setTimeout() workaround.
refer to the input element with this.myInput you have to define it inside your Component as a ViewChild.
Here is the example of Modal Component which will autofocus its input after showing itself on the page.
Javascript:
Hi! I tried this solution and it works fine: the input focuses when the component is loaded, but then the keyboard cannot be closed afterwards. Whenever I try to hide it, it pops up again. Is there a way of solving this?
I tried ngAfterViewInit() insead of ngAfterViewChecked(), because this way it should be called only once. But in this case, when the component loads, the input is focused (and keyboard appears) only for a second, then keyboard closes back again and the field is no longer focused. I don´t know why, seems like something else is resetting the setFocus command.