Ionic 3 Framework - setFocus on opened modal 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:

ionViewLoaded() {
    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() {

So that is clean setFocus() solution for Ionic without using setTimeout() workaround.


In order to be able to 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:

  selector: 'location-modal-create',
  templateUrl: 'modal-create.html'
export class LocationCreateModal {
  private location: FormGroup;

  @ViewChild('myInput') myInput;

    public platform: Platform,
    public params: NavParams,
    public viewCtrl: ViewController,
    private formBuilder: FormBuilder
  ) {
    this.location ={
      name: ['', Validators.required],
    this.params = params;
    this.viewCtrl = viewCtrl;

  ngAfterViewChecked() {

  dismiss() {


      New Location
    <ion-buttons end>
      <button ion-button (click)="dismiss()">
        <span ion-text color="primary" showWhen="ios">Cancel</span>
        <ion-icon name="close" hideWhen="ios"></ion-icon>

  <form [formGroup]="location" (ngSubmit)="submit()">

      <ion-label floating>Location name</ion-label>
      <ion-input #myInput formControlName="name" type="text"></ion-input>

    <div padding *ngIf="location.valid">
      <button ion-button block>Create Location</button>
    <div padding *ngIf="!location.valid">
      <button ion-button block disabled outline>Please fill Location data</button>