typescript 如何在 ionic 2(搜索栏)中进行自动完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39093052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do auto-complete in ionic 2 (search-bar)
提问by balaji
I am trying to do an auto complete in my search bar what i have done so far is.
我正在尝试在我的搜索栏中自动完成到目前为止我所做的。
I have an array with some strings. and then i am trying to list in my items it i am able to search the particualr item.
我有一个带有一些字符串的数组。然后我试图在我的项目中列出它我可以搜索特定的项目。
But my requirement is not to display the items in a list. I have to make on clicking the search bar all the strings in array should come and the i have to make a search.
但我的要求不是在列表中显示项目。我必须点击搜索栏,数组中的所有字符串都应该出现,我必须进行搜索。
<ion-header>
<ion-navbar>
<ion-title>search</ion-title>
</ion-navbar>
<ion-toolbar primary >
<ion-searchbar (ionInput)="getItems($event)" autocorrect="off"></ion-searchbar>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
Code for search.ts file:
search.ts 文件的代码:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
/*
Generated class for the SearchPage page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
templateUrl: 'build/pages/search/search.html',
})
export class SearchPage {
private searchQuery: string = '';
private items: string[];
constructor(private navCtrl: NavController) {
this.initializeItems();
}
initializeItems() {
this.items = [
'Amsterdam',
'Bogota',
]
}
getItems(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);
})
}
}
}
Question :
问题 :
How to get the value of an array through auto complete in ionic 2.
如何通过离子2中的自动完成获取数组的值。
回答by sebaferreras
In order to achieve that, you just need to add a small thing to your code. Please take a look at this plunker.
为了实现这一点,您只需要在代码中添加一个小东西。请看看这个 plunker。
Like you can see there, with the showList
variable we can show the results only after the user has searched something.
就像您在那里看到的那样,showList
只有在用户搜索某些内容后,我们才能使用变量显示结果。
<ion-list *ngIf="showList">
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
We first set that variable to false
in the constructor
and then we set it to true
inside the getItems(...)
method.
我们首先将该变量设置为false
in constructor
,然后将其设置true
为getItems(...)
方法内部。