Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do auto-complete in ionic 2 (search-bar)

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:

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.

like image 366
balaji Avatar asked Aug 23 '16 05:08

balaji


People also ask

How do I clear my search bar in ionic?

Clear Button​ A clear button is displayed when a searchbar has a value or upon entering input in the searchbar's text field. Clicking on the clear button will erase the text field and the input will remain focused.


1 Answers

In order to achieve that, you just need to add a small thing to your code. Please take a look at this plunker.

Like you can see there, with the showList variable we can show the results only after the user has searched something.

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

like image 90
sebaferreras Avatar answered Oct 14 '22 23:10

sebaferreras