How to focus ion-searchbar on button click

一世执手 提交于 2019-12-05 19:57:08

Hope you can do it using below code.Just try it using setTimeout as shown below.

.html

<ion-searchbar #search (ionCancel)="cancelSearch($event)" 
[showCancelButton]="true" [(ngModel)]="artists"></ion-searchbar>

<ion-buttons end>
   <button [hidden]="showSearch" (click)="(showSearch = !showSearch) && focusButton()" ion-button icon-only>
    <ion-icon  name="search"></ion-icon>
  </button>
</ion-buttons>

.ts

@ViewChild('search') search : any;

focusButton(): void {
    setTimeout(() => {
      this.search.setFocus();
    }, 500);
  }
  1. Add reference into the template

    <input #inputEl> or <ion-searchbar #inputEl> whatever you use as input

  2. Import ViewChild on the top of .ts and define a reference variable in component class

    import { ViewChild } from '@angular/core';
    @ViewChild('inputEl') inputElRef;
    
  3. Use nativeElement to access focus() function

    this.inputElRef.nativeElement.focus();

For those working with Angular 8 and Ionic 4 one can set the flag static: false which will consider that an *ngIf is involved and hiding the search bar for example. As soon *ngIf displays again the visual component (e.g. ion-searchbar)

@ViewChild('searchInput', {static: false}) searchInput: IonSearchbar;

  constructor() { }

  public setSearchbarVisible(isVisible) {
    this.isSearchbarOpened = isVisible;
    if (isVisible) {
      setTimeout(() => {
        this.searchInput.setFocus();
    }, 100);
    }
  }

Adding a type to the searchInput will also help with method and property insights, like setFocus(). That is neat code without daring to touch the wraped native elements.

1-) Import IonSearchBar Element

import { IonSearchbar} from '@ionic/angular';

2-) Create ViewChild for IonSearchBar

@ViewChild(IonSearchbar) myInput: IonSearchbar;

3-) Set focus with timeout

setTimeout(() => { this.myInput.setFocus(); }, 150);

--

Open Request feature here: ion-searchbar autofocus #17745

Best regards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!