【问题标题】:How to do auto-complete in ionic 2 (search-bar)如何在 ionic 2 中自动完成(搜索栏)
【发布时间】:2016-12-29 19:16:13
【问题描述】:

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

我有一个包含一些字符串的数组。然后我试图在我的项目中列出我可以搜索特定项目。

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

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

问题:

如何在ionic 2中通过自动完成获取数组的值。

【问题讨论】:

  • 能否请您也添加您的视图代码?
  • 我已经添加了 HTML 和 .ts 文件的代码,请看一下。我是新手
  • 我在 Ionic 文档中看到他们有搜索栏的自动完成属性,你试过吗? ionicframework.com/docs/v2/api/components/searchbar/Searchbar
  • 我不知道你能帮我如何使用自动完成属性
  • '我必须在单击搜索栏时必须使数组中的所有字符串都应该出现并且我必须进行搜索'是什么意思?

标签: angular typescript ionic-framework ionic2 ionic3


【解决方案1】:

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

正如您在此处看到的那样,使用 showList 变量,我们只能在用户搜索某些内容后显示结果。

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

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

【讨论】:

  • 我做了同样的事情,但在 this.items 数组中出现错误
  • @MohanGopi 为避免在开头显示取消按钮,添加[showCancelButton]="false"。我创建了这个new plunker,当搜索栏的内容为空时,我会在其中隐藏结果。希望这会有所帮助:)
  • @sebaferreras plunker 链接已损坏..你能更新一下吗?
  • @varunaaruru 答案的 plunker 已更新。如果这是您要找的,请告诉我。
  • 感谢 :) 它的工作并在我的应用程序中帮助了我 :) @sebaferreras
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-12
相关资源
最近更新 更多