Skip to content

V3.1.1 SearchBar setFocus() not setting focus #11453

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
HairyCream opened this issue Apr 30, 2017 · 27 comments
Closed

V3.1.1 SearchBar setFocus() not setting focus #11453

HairyCream opened this issue Apr 30, 2017 · 27 comments
Assignees
Labels
ionitron: v3 moves the issue to the ionic-v3 repository

Comments

@HairyCream
Copy link

Ionic version: (check one with "x")
[X] 3.1.1

I'm submitting a ... (check one with "x")
[X] bug report

Current behavior:
Using setFocus() on SearchBar property inside IonViewDidEnter does not set the focus.

Expected behavior:
The focus should be in the searchbar entry area after the page is entered

Steps to reproduce:

  1. ionic start setFocus blank
  2. cd setFocus
  3. update home.html and home.ts as below
  4. ionic serve

Related code:
home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <ion-searchbar #si (ionInput)="onInput($event)"></ion-searchbar>
</ion-content>

home.ts

import { Component, ViewChild } from '@angular/core';
import { Searchbar } from 'ionic-angular';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('si') searchInput: Searchbar;
  constructor() {
  }

  ionViewDidEnter() {
    console.log("setFocus()", this.searchInput);
    this.searchInput.setFocus();
  }

  onInput(ev: any) {
    console.log(ev.target.value);
  }
}

Other information:
I've only tried this in a browser (Chrome) using ionic serve

Ionic info: (run ionic info from a terminal/cmd prompt and paste output below):

D:\dev\testSetFocus>ionic info
global packages:
    @ionic/cli-utils : 1.0.0-rc.0
    Cordova CLI      : 6.5.0
    Ionic CLI        : 3.0.0-rc.0
local packages:
    @ionic/app-scripts              : 1.3.6
    @ionic/cli-plugin-cordova       : 1.0.0-rc.0
    @ionic/cli-plugin-ionic-angular : 1.0.0-rc.0
    Ionic Framework                 : ionic-angular 3.1.1
System:
    Node       : v6.10.2
    OS         : Windows 10
    Xcode      : not installed
    ios-deploy : not installed
    ios-sim    : not installed
@jgw96
Copy link
Contributor

jgw96 commented May 1, 2017

Hello, thanks for opening an issue with us, we will look into this.

@ekhmoi
Copy link

ekhmoi commented May 2, 2017

Hey I'm using as a workaround
ngOnInit() { setTimeout(() => { this.username.setFocus(); }, 150); }

@simonweber96
Copy link

Still having this issue? Why is it closed without any comments?

@manucorporat
Copy link
Contributor

manucorporat commented Jun 14, 2017

@simonweber96 @HairyCream desktop or device?

@simonweber96
Copy link

@manucorporat on desktop it is working perfectly. Even in the Lab serve-environment both Android and iOS are behaving correctly. But when I build the app and run it on the device directly, Android is working, but iOS is not. Weird behaviour ...

@manucorporat
Copy link
Contributor

@simonweber96 not that weird. Unfortunately this is likely an unfixable issue. Input.focus() only works if called inside an stack initiated by a touch/mouse/keyboard event.

It is known limitation of WK and UIWebView.

@HairyCream
Copy link
Author

I'm now on Ionic 3.4.0, and it still doesn't work in browser, Android or iOS.
If this will never work, ... "known limitation", then shouldn't the Ionic documentation ( API>SearchBar>setFocus() ) be updated to reflect the current situation?

@AmitMY
Copy link
Contributor

AmitMY commented Jun 21, 2017

@HairyCream If it doesn't work in browser, can you make a reproduction plunker/repo? It works for me in browser. On device is a different matter, as manu mentioned.

@jgw96
Copy link
Contributor

jgw96 commented Jun 21, 2017

@HairyCream , any luck on making that reproduction plunker or repo?

@HairyCream
Copy link
Author

First, if @manucorporat is correct, and this is a known limitation, then the issue should be re-queued for a documentation update. ... or am I missing something?

But, by "browser" I mean the browser session initiated by an ionic serve command.
The easiest way to reproduce is to follow the "Steps to reproduce:" in the first post.
I have tried this with both Chrome (59.0.3071.109) and Firefox (ionic serve -w firefox / 54.0 32-bit) under Win 10 Pro.

@ErbolLab
Copy link

OMG, even such a trivial task as setting a "focus" now requires so much effort and nerves.

I tried this:

ionViewDidLoad(): void {
  this.searchInput.setFocus();
}

this:

ionViewDidLoad(): void {
  setTimeout(() => {
    this.searchInput.setFocus();
  }, 300);
}

and even this:

  ionViewDidLoad(): void {
    let nativeEl = this.searchInput.getNativeElement()
    let input = nativeEl.getElementsByTagName('input');
    if (input.length) {
      input[0].focus();
    }
  }

nothing works.

Is this issue somehow relates to wkwebview?

@AmitMY
Copy link
Contributor

AmitMY commented Jun 23, 2017

@Erbolking This issue relates to iOS's UI/WK web views.

Unfortunately this is likely an unfixable issue. Input.focus() only works if called inside an stack initiated by a touch/mouse/keyboard event.

It is known limitation of WK and UIWebView.

So it is not an issue with ionic.

@ErbolLab
Copy link

So it is not an issue with ionic.

@AmitMY thanks

One possible solution:
ionic-team/ionic-plugin-keyboard#274 (comment)

@jmalberola
Copy link

@HairyCream I've just tested your solution and at least it works for me (Ionic Framework 3.3.0, CLI 2.2.3 and physical device Android 5.1.1). Thanks.

@ggravand
Copy link

Any updates on this - is there any hope of a fix or should the issue be closed with a documentation update? I have no problem with the limitation suggested by @manucorporat above but it does not seem to work: I experience the problem if I invoke setFocus() from inside a stack originating from a tap on an item in the auto search results (using wkwebview). Can anybody confirm they have observed this working or was it just an assumption that it would work?

I have applied the suggested patch to no avail. I have tried the setTimeout suggestion, also to no avail (I don't understand how the latter suggestion could work as it contradicts the requirement that the event must originate from a touch/mouse/keyboard event?).

Any status update on the issue as well as new ideas or suggestions are very welcome!

@chukwu
Copy link

chukwu commented Sep 17, 2017

I figured this out the brutal way. The problem isn't a deadlock. I had to invite KEYBOARD plugin into the picture as though i wanted to reinvent the wheels:

  1. Step 1: Make sure the keyboard plugin is installed and configured (In many cases, it already is)
  2. Step 2: Add <preference name="KeyboardDisplayRequiresUserAction" value="false" /> to config.xml

Code

export class GeneralsearchPage{
  
  @ViewChild("searchbar") searchbar:Searchbar;

  constructor(private keyboard: Keyboard){
        //bla bla
  }

  ionViewDidLoad() {
    setTimeout(()=>{
      this.searchbar.setFocus();
      this.keyboard.show();
    },2000);


    this.keyboard.onKeyboardShow().subscribe((data)=>{
      this.searchbar.setFocus();
    })
    
  }
}

@keithdmoore
Copy link
Contributor

keithdmoore commented Dec 22, 2017

@chukwu Thanks for sharing! I ended up doing the below, which worked out great for me. What device did you test this on? I was curious why the 2000ms on the setTimeout? Just to be on the safe side or did you have issues on slower devices?

import { first } from 'rxjs/operators/first';

// I only want this to fire once and I do not want to deal with unsubscribing   
this.keyboard.onKeyboardShow().pipe(first()).subscribe(()=>{
      this.searchbar.setFocus();
});

setTimeout(()=>{
      this.searchbar.setFocus();
      this.keyboard.show();
}, 500);

@chukwu
Copy link

chukwu commented Dec 23, 2017

@keithdmoore .... The delayed timeout doesn't make much of a difference. Just make sure device/plugin is ready and view is loaded.

@anjildhamala
Copy link

I'd like to add a suggestion to everyone that is going through this issue either now or will stumble on it in the future. I'd suggest logging your searchbar viewchild before setting focus on it. If it comes back as undefined, that probably means your setFocus() is being called before ionic searchbar has initialized. This could happen because of *ngIf because the element is not initialized until it passes the conditional flag and could cause delay in between creation and using one of its function. In that case, use a small timeout (150ms) and then log it again. If you do see it, then set the focus within that timeout.

@keithdmoore
Copy link
Contributor

@anjildhamala I found that I didn't need to use the onKeyboardShow event listener. I just needed the timeout.

@michaelkariv
Copy link

I have the same problem on Chrome on Windows desktop.

@ericksm3
Copy link

ericksm3 commented Jul 3, 2018

i made the focus work with a bigger timeout and had to add the show method on the keyboard (tested only on android). ionic 2 and 3

Code:

import { Keyboard } from '@ionic-native/keyboard';
and
ionViewDidLoad() { setTimeout(() => { this.myInput.setFocus(); this.keyboard.show(); },2000); }

@josh-m-sharpe
Copy link

Is there a reason why the setFocus documentation hasn't been updated yet?

@SaurabhPrajapati
Copy link

SaurabhPrajapati commented Aug 3, 2018

after reading too many threads, i have tried below code and it is working fine for iOS.

ionViewDidEnter(){
    let self = this;
    setTimeout(() => {
      self.ngZone.run(()=>{
        self.searchbar.setFocus();
      })
    }, 500)
  }

For iOS, if someone want to show cancel button always then you can add below css,

.searchbar-ios-cancel {
      display: block;
      padding-left:8px !important;
    }

So basically , to setFocus work on iOS , you need to setFocus in viewDidEnter instead of iosViewWillEnter/ionViewDidLoad.

keyboard.show will not work at all in iOS, Please check below

show()
Platforms:ANDROID BLACKBERRY 10 WINDOWS 

Force keyboard to be shown.

Ref - https://ionicframework.com/docs/native/keyboard/

@josh-m-sharpe
Copy link

@SaurabhPrajapati does setfocus inside ngzone open the keyboard on ios?

@adamdbradley adamdbradley added the ionitron: v3 moves the issue to the ionic-v3 repository label Nov 1, 2018
@imhoffd imhoffd removed ionitron: v3 moves the issue to the ionic-v3 repository labels Nov 28, 2018
@Ionitron Ionitron added the ionitron: v3 moves the issue to the ionic-v3 repository label Nov 28, 2018
@ionitron-bot
Copy link

ionitron-bot bot commented Nov 28, 2018

This issue has been automatically identified as an Ionic 3 issue. We recently moved Ionic 3 to its own repository. I am moving this issue to the repository for Ionic 3. Please track this issue over there.

If I've made a mistake, and if this issue is still relevant to Ionic 4, please let the Ionic Framework team know!

Thank you for using Ionic!

@ionitron-bot
Copy link

ionitron-bot bot commented Nov 28, 2018

Issue moved to: ionic-team/ionic-v3#280

@ionitron-bot ionitron-bot bot closed this as completed Nov 28, 2018
@ionitron-bot ionitron-bot bot locked and limited conversation to collaborators Nov 28, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
ionitron: v3 moves the issue to the ionic-v3 repository
Projects
None yet
Development

No branches or pull requests