当我点击搜索图标时,它会打开栏上的搜索框,但我希望它能够专注于该字段并打开键盘。
我如何实现这一目标?
请在下面找到我的home.html
和home.ts
代码
home.html的
<ion-header>
<ion-navbar color="primary">
<button *ngIf="!toggled" ion-button icon-only menuToggle><ion-icon name="menu"></ion-icon></button>
<!-- Title -->
<ion-title *ngIf="!toggled">Início</ion-title>
<!-- Search Bar -->
<ion-searchbar *ngIf="toggled" [(ngModel)]="searchTerm" [showCancelButton]="true" (ionCancel)="toggleSearch()" (ionInput)="triggerInput($event)"></ion-searchbar>
<!-- Search Icon -->
<ion-buttons end *ngIf="!toggled">
<button ion-button icon-only (click)="toggleSearch()"><ion-icon name="search"></ion-icon></button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
home.ts
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
@Component( {
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
toggled: boolean;
searchTerm: String = '';
items: string[];
constructor( public navCtrl: NavController, public navParams: NavParams ) {
this.toggled = false;
this.initializeItems();
}
ionViewDidLoad() {
console.log( 'ionViewDidLoad HomePage' );
}
toggleSearch() {
this.toggled = this.toggled ? false : true;
}
initializeItems() {
this.items = ['Amsterdam','Bogota','Mumbai','San José','Salvador'];
}
triggerInput( ev: any ) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
let val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
}
答案 0 :(得分:2)
我解决了这个问题:
import { Searchbar } from 'ionic-angular'; import { ViewChild } from '@angular/core';
export class HomePage { @ViewChild('searchbar') searchbar:Searchbar; ... some code }
toggleSearch() { setTimeout(() => { this.searchbar.setFocus(); }, 5); }
在HTML中添加 #searchbar 标记,如下所示:
<ion-searchbar #searchbar ...some code...></ion-searchbar>
请参阅离子论坛上的more