Appear list only when searchbar is filled - Ionic 3

0

Hello, I'm using this searchbar code and it's working. But I want the list of items to appear ONLY when I have something written on the searchbar. Basically I DO NOT want a "list of all items" to appear, only the items filtered when typing in the searchbar. If you delete the searchbar content the items should disappear again. What should I do? I've done a lot of research on the internet and I do not think anything. Thanks in advance.

HTML:

<ion-content padding>
    <ion-searchbar (ionInput)="getItems($event)" placeholder="" ></ion-searchbar>
        <ion-list>
          <button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">{{ item }}</button>
        </ion-list>
</ion-content>

TS:

export class SearchPage {
  searchQuery: string = '';
  items: string[];

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.initializeItems();   
  }

  initializeItems() {
    this.items = [
      'item 1',
      'item 2',
    ];
  }

  getItems(ev: any) {
    this.initializeItems();

    let val = ev.target.value;

    if (val && val.trim() != '') {
      this.items = this.items.filter((item) => {
        return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

    itemTapped(event, item) {
      this.navCtrl.push(
          SearchPage, {item: item}
      );
    }
}
    
asked by anonymous 21.11.2017 / 05:05

1 answer

0

You can do a * ngIf in the template by seeing if the searched field is different from null, type:   *ngIf="termoPesquisado"

Or even replace this part:

if (val && val.trim() != '') {
  this.items = this.items.filter((item) => {
    return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
  })
}

so:

if (val && val.trim() != '') {
  this.items = this.items.filter((item) => {
    return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
  })
} else {
  return []; retorna array vazia
}
    
28.11.2017 / 03:23