问题
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.
回答1:
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);
}
回答2:
Add reference into the template
<input #inputEl>or<ion-searchbar #inputEl>whatever you use as inputImport
ViewChildon the top of .ts and define a reference variable in component classimport { ViewChild } from '@angular/core'; @ViewChild('inputEl') inputElRef;Use
nativeElementto accessfocus()functionthis.inputElRef.nativeElement.focus();
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/45786205/how-to-focus-ion-searchbar-on-button-click