Setting Focus to an Input in Ionic

I found a solution as a Directive

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

add to app.module

import { Focuser } from "../directives/focuser/focuser";

@NgModule({
  declarations: [ ... 
                         Focuser  ]

use the directive.

<ion-input focuser . . . >

1 Like