如何在 Ionic 4 的搜索栏上使用自动完成功能?

How to use autocomplete on search bar on Ionic 4?

我正在寻找一些示例,但找不到任何人使用谷歌搜索,我只是想要硬编码 2 或 3 个单词,非常感谢。我必须在 ionic 3 上寻找吗?还是在 angular2 中更好?

在您的 html 文件中:

     <ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
     <ion-list *ngIf="isItemAvailable">
         <ion-item *ngFor="let item of items">{{ item }}</ion-item>
     </ion-list>

在你的 ts 文件中:

     // Declare the variable (in this case and initialize it with false)
     isItemAvailable = false;
     items = [];

     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);
             })
         } else {
             this.isItemAvailable = false;
         }
     }

Mohan Gopi 的回答是完整的,但是为了使用 debounce 属性,您必须使用 ionChange 事件而不是 ionInput 事件。

<ion-searchbar type="text" debounce="500" (ionChange)="getItems($event)"></ion-searchbar>
...
...

这样事件将在用户停止键入后(自上次按键后 500 毫秒后)触发,而不是每当按下一个键时触发。

只是想分享一些我自己尝试过的东西。我已经实现了 Angulars material 设计 (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>

在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;
}

虽然问题是关于 ion-searchbar 的,但也许有人也想像我一样使用普通的 ion-input。没有明确的图标,但我可以接受,或者只是在离子输入旁边添加一个。可能有办法将离子搜索栏变成普通的离子输入样式吗?虽然在文档中找不到它。