Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus ion-searchbar on button click

I am trying to focus ion-searchbar on button click but it is not working. This is my code

Typescript

@ViewChild('search') search:ElementRef;

focusButton(){
       console.log(this.search);   //Searchbar {_config: Config, _elementRef: ElementRef, _renderer: RendererAdapter, _componentName: "searchbar", _mode: "md", …}
       console.log(this.search.nativeElement); //  null
       this.search.nativeElement.focus();      //  Cannot read property 'focus' of undefined
        this.search.nativeElement.setFocus();      // Cannot read property 'setFocus' of undefined

}

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>

The console output is above in comments with code.

like image 503
shah Avatar asked Aug 20 '17 19:08

shah


1 Answers

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);
  }
like image 102
Sampath Avatar answered Oct 18 '22 09:10

Sampath