Search code examples
angularsearchionic-frameworkionic2searchbar

Ionic 2 - How To Edit Searchbar Values Programmatically


How can I modify an ionic searchbar programatically in Ionic 2? I searched this for a while and did not come across anything that solves it.

I want to access & modify the default methods of the searchbar object from the searchview.ts. (e.g. inside onClear(), call onCancel() & navigate to a different view). This is the searchbar in my html file.

<ion-searchbar [showCancelButton]="true" (ionClear)="onClear()">
</ion-searchbar>

I want to do something like;

onClear(){
    var searchbar = this.searchbar // reference the search bar in the html file, but how do I get this?
    searchbar.onCancel();
    this.navigateToHome();
}

Thanks in advance for your help!

Edit: added code sample. Modified the example to calling onCancel() from onClear(), instead of vice versa.


Solution

  • I figured I did not know how to ask the question right, I should have asked how do you access a child component/view in the html from the controller;

    <ion-searchbar #mySearchBar (ionCancel)="onCancel()"></ion-searchbar>
    

    Then access it like this;

    @ViewChild('mySearchBar') searchbar:Searchbar;
    

    and use it like this;

    this.searchbar.ionCancel()
    

    The whole code;

    import { Component, ViewChild } from '@angular/core';
    import { Searchbar } from 'ionic-angular';
    
    export class DictionaryPage {
        @ViewChild('mySearchBar') searchbar:Searchbar;
    
        constructor(){
             this.searchbar.ionCancel()}
    }