Reputation: 95
How to code the click and view search bar in ionic 2 application. In that one the search icon only shows first, when i click the search icon the the search bar will show.
Upvotes: 1
Views: 12645
Reputation: 7719
ts
export class Page1{
public toggled: boolean = false;
constructor() {
this.toggled = false;
}
public toggle(): void {
this.toggled = !this.toggled;
}
}
html
<div>
<ion-icon *ngIf="!toggled" (click)="toggle()" name="search"></ion-icon>
<ion-searchbar
*ngIf="toggled"
[(ngModel)]="someValue"
(ionInput)="searchThis($event)"
(ionCancel)="cancelSearch($event)"
(ionClear) = "cancelSearch($event)"
[showCancelButton]="true">
</ion-searchbar>
</div>
In your cancelSearch()
you can call this.toggle()
to show the icon again.
Upvotes: 8
Reputation: 1818
I think @Ivaro18's answer is perfect.
I would just like to complement with my example set up according to his response.
home.ts
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
@Component( {
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
toggled: boolean;
searchTerm: String = '';
items: string[];
constructor( public navCtrl: NavController, public navParams: NavParams ) {
this.toggled = false;
this.initializeItems();
}
ionViewDidLoad() {
console.log( 'ionViewDidLoad HomePage' );
}
toggleSearch() {
this.toggled = this.toggled ? false : true;
}
initializeItems() {
this.items = ['Amsterdam','Bogota','Mumbai','San José','Salvador'];
}
triggerInput( 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);
})
}
}
}
home.html
<ion-header>
<ion-navbar color="primary">
<button *ngIf="!toggled" ion-button icon-only menuToggle><ion-icon name="menu"></ion-icon></button>
<!-- Title -->
<ion-title *ngIf="!toggled">Início</ion-title>
<!-- Search Bar -->
<ion-searchbar *ngIf="toggled" [(ngModel)]="searchTerm" [showCancelButton]="true" (ionCancel)="toggleSearch()" (ionInput)="triggerInput($event)"></ion-searchbar>
<!-- Search Icon -->
<ion-buttons end *ngIf="!toggled">
<button ion-button icon-only (click)="toggleSearch()"><ion-icon name="search"></ion-icon></button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item *ngFor="let item of items">
{{ item }}
</ion-item>
</ion-list>
</ion-content>
More info: For more information, Check out the API docs.
Upvotes: 2