M. *_*cal 3 autocomplete searchbar ionic4
我正在寻找一些示例,但是看不到有人在搜索它,我只想对2或3个单词进行硬编码,非常感谢。我是否需要寻找离子3?还是在angular2更好?
在你的HTML
<ion-searchbar type="text" debounce="500" (ionInput)="getItems($event)"></ion-searchbar>
<ion-list *ngIf="isItemAvailable">
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
Run Code Online (Sandbox Code Playgroud)
在您的ts文件中
this.isItemAvailable = false; // initialize the items with false
initializeItems(){
this.items = ["Ram","gopi", "dravid"];
}
getItems(ev: any) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
const val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.isItemAvailable = true;
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
Run Code Online (Sandbox Code Playgroud)
只是想分享一些我自己尝试过的东西。我已经从 Angulars 材料设计(https://material.angular.io/components/autocomplete/overview)实现了自动完成,但它看起来与其余的离子输入组件并不完全一样。我也尝试了 ion-searchbar 但我不喜欢搜索输入,我想要一个普通的 ion-input 所以我这样做了:
html:
<ion-list>
<ion-item>
<ion-label position="floating">Supplier*</ion-label>
<ion-input (ionChange)="onSearchChange($event)" [(ngModel)]="supplier"></ion-input>
</ion-item>
<ion-item *ngIf="resultsAvailable">
<ion-list style="width: 100%; max-height: 200px; overflow-y: scroll;">
<ion-item *ngFor="let result of results" (click)="supplierSelected(result)" button>
<ion-label>{{result}}</ion-label>
</ion-item>
</ion-list>
</ion-item>
</ion-list>
Run Code Online (Sandbox Code Playgroud)
在 component.ts 中:
resultsAvailable: boolean = false;
results: string[] = [];
ignoreNextChange: boolean = false;
onSearchChange(event: any) {
const substring = event.target.value;
if (this.ignoreNextChange) {
this.ignoreNextChange = false;
return;
}
this.dataService.getStrings(substring).subscribe((result) => {
this.results = result;
if (this.results.length > 0) {
this.resultsAvailable = true;
} else {
this.resultsAvailable = false;
}
});
}
supplierSelected(selected: string) :void {
this.supplier = selected;
this.results = [];
this.resultsAvailable = false;
this.ignoreNextChange = true;
}
Run Code Online (Sandbox Code Playgroud)
当然,问题是关于 ion-searchbar,但也许有人也想使用像我这样的普通 ion-input。没有清晰的图标,但我可以忍受,或者只是在离子输入旁边添加一个。可能有办法将离子搜索栏变成正常的离子输入样式吗?虽然在文档中找不到它。
小智 5
Mohan Gopi的答案是完整的,但是为了利用该debounce属性,您必须使用ionChange事件而不是ionInput事件。
<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
...
...
Run Code Online (Sandbox Code Playgroud)
这样,事件将在用户停止键入后(自上次按下键以来经过500毫秒后)触发,而不是在每次按下键时触发。