0

In my snippet i have tried to set focus for first input text field. But when the page loaded it gets focused and lose the focus suddenly & closes the keyboard. Can anyone please tell me to achieve this.

<ion-input [(ngModel)]="username" name="username" type="text" #username="ngModel" spellcheck="false" autocapitalize="off" autofocus clearInput required></ion-input>
Mathankumar
  • 105
  • 1
  • 11

2 Answers2

0

add view Reference with (#) for that In your html,

<ion-input [(ngModel)]="username" name="username" type="text" #username="ngModel" spellcheck="false" autocapitalize="off" autofocus clearInput required  #focusInput></ion-input>

In your component.ts Import ViewChild and set focus of this(#focusInput) Input

Like

import {Component, ViewChild} from '@angular/core';

@ViewChild('focusInput') myInput;

ionViewDidEnter() {
       this.myInput.setFocus();
    }

This gonna help.

Aneri Vala
  • 528
  • 3
  • 11
  • 1
    Thanks Aneri. It is not working me. It showing same as previous. It open the keyboard and hides suddenly & also lose the focus. – Mathankumar May 22 '18 at 05:23
0
<input #exampleInput />
@ViewChild('exampleInput') exampleInput: ElementRef;

setTimeout(() => {
    this.exampleInput.nativeElement.focus();
}, 300);

This works for me.

Note: You may want to use this timeout in ngAfterViewInit method or other places, and 300 milliseconds delay sounds enough in my tested devices.

SidMorad
  • 954
  • 12
  • 19
  • Thanks Sid. It is not working me. Shows the same screen. – Mathankumar May 22 '18 at 05:22
  • Sorry Sid . I have tried with only 300 millisecond. For 300 it is not working. Above 300 hundred it is working but sometimes not working. I have tried with 400 & 500, It take some delay to get focus. Is there any way to achieve this without delay. – Mathankumar May 22 '18 at 06:17
  • I also experienced different result in `emulator` | `real device` | `--aot` flag was in use, so for me `--aot` flag + `real device` combination was working fine. And I haven't test it in old-phones which I am suspicious may not work well in compare with new-phones(=better CPU). And no I don't know any other way without using timeout, please let me know if you find one! :^) – SidMorad May 22 '18 at 06:25
  • Anyway Thanks for your solution. I have one more doubt. Can you please check this. https://stackoverflow.com/questions/50460216/gray-screen-before-splash-screen-in-ionic2-app – Mathankumar May 22 '18 at 06:29