Appear list only when Searchbar is filled - Ionic 3

Asked

Viewed 359 times

0

Hi, I’m using this Separchbar code and it’s working. But I want the list of items to appear ONLY when you have something written in the Archbar. Basically I DO NOT want a "list of all items" to appear, only the filtered items when typing in the Archbar. If you delete the content from Archbar the items should disappear again. What should I do? I’ve searched a lot on the internet and I can’t find 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}
      );
    }
}

1 answer

0


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

Or replace that part:

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

therefore:

if (val && val.trim() != '') {
  this.items = this.items.filter((item) => {
    return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
  })
} else {
  return []; retorna array vazia
}
  • Thanks for the answer! I managed to solve otherwise already, but this your way seems much cleaner and efficient. I will try.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.