angular - 如何在 ionic 2(搜索栏)中进行自动完成

标签 angular typescript ionic-framework ionic2 ionic3

我正在尝试在我的搜索栏中进行自动完成,我目前所做的是。

我有一个包含一些字符串的数组。然后我试图在我的项目中列出它我能够搜索 particualr 项目。

但我的要求不是在列表中显示项目。我必须点击搜索栏,数组中的所有字符串都应该出现,我必须进行搜索。

<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>

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

问题:

How to get the value of an array through auto complete in ionic 2.

最佳答案

为了实现这一点,您只需在代码中添加一个小东西。请看this plunker .

如您所见,使用 showList 变量,我们可以仅在用户搜索后显示结果。

  <ion-list *ngIf="showList">
    <ion-item *ngFor="let item of items">
      {{ item }}
    </ion-item>
  </ion-list>

我们首先在 constructor 中将该变量设置为 false,然后在 getItems(.. .) 方法。

关于angular - 如何在 ionic 2(搜索栏)中进行自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39093052/

相关文章:

javascript - 从 Angular 2 中的存储数组中删除项目

typescript - 用 bind 包装 console.log 以保持调用者上下文

php - 语法错误 : Unexpected token < at Object. 解析( native )

css - ionic 框架无法设置按钮图标大小

angular - 我如何为 Router Guard Jasmine 测试模拟 RouterStateSnapshot

javascript - 如何从列表中过滤数据并以 Angular 从数据中删除现有房间

angular - 带有动态递归模板的响应式(Reactive)表单

javascript - 这些绑定(bind)方法在 Angular 上有什么区别?

angular - RxJS 6 过滤并映射一个可观察的项目数组

iOS 模拟器允许 cordova 地理定位,使用 ionic 框架