Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear text in ion-searchbar

I have a search bar

<div id="search"><ion-searchbar [(ngModel)]="searchQuery" (change)="onChange($event)" (ionClear)="onCancel($event)" (ionInput)="onInput($event)" debounce="1"></ion-searchbar></div>

How do I, from the ts file clear the text the user has entered?

Here is the ts file function that tries to clear the search bar text.

.
private searchQuery: string = null;
.

  subscribeEvents() {
    this.events.subscribe('mapFilter:update', (data) => {
      this.employeeModel = data[0].employeeModel;
      if (data[0].fromClearFilters) {
        this.searchQuery = '';
      }
      this.getMarkers();
      this.getPosition();
    });
  }

this.searchQuery = ''; does reset the filter but the text remains

Thanks

I am using Ionic 2

like image 341
Richard Avatar asked Dec 03 '22 14:12

Richard


2 Answers

First, add an identifier to your HTML element

<ion-searchbar #mySearchbar ...>

Then, import ViewChild:

import { ViewChild } from '@angular/core';

Then, import Searchbar

import { Searchbar } from 'ionic-angular';

Add it as a property:

@ViewChild('mySearchbar') searchbar: Searchbar;

Then, fire the onInput event and pass a null identifier (so your onInput event listener knows its you)

this.searchbar.clearInput(null);

like image 82
DJ. Avatar answered Dec 20 '22 18:12

DJ.


Workable Solution for ionic 5.4.16 & Angular 8.2.14 : Similar to DJ.'s answer, but for different version.

1.Your ion-searchbar with #mySearchbar tag

  <ion-searchbar #mySearchbar1 #q (keyup.enter)="navigateSearchPage(q.value)"  placeholder="Search Product Name" style="padding: 0 10px" ></ion-searchbar>

2.Import and place the following code

import {ViewChild} from '@angular/core';
import {IonSearchbar} from '@ionic/angular';

@ViewChild('mySearchbar', {static: false}) searchbar: IonSearchbar;

3.Clear the searchbar (place this code to the function that you will call to clear the searchbar.

this.searchbar.value = null;
like image 33
kw88 Avatar answered Dec 20 '22 16:12

kw88