Ion-search: keep cancel button visible


#1

I’ve noticed that the CANCEL button in the ion-searchbar disappears on blur in my header menu. Is there a way to keep that visible at all times (or until I want it to go away)?

I’m changing the page content to show search results. If the user scrolls though the results, the button disappears, which could be confusing since the user will want to dismiss search results at some point to return the page to it’s normal state. As it is now, they first need to return focus to the search field (which restores the cancel button’s visibilty) and then hit the cancel button.

<ion-header>
  <ion-navbar>
    <ion-buttons end>
        <button ion-button icon-only (tap)="showOptions($event,'discover')"  *ngIf="!hideOptionsButton">
            <ion-icon name="options"></ion-icon>
        </button>
    </ion-buttons>
    <form (ngSubmit)="submitSearch($event)">
      <ion-searchbar
      placeholder="Global Search"
      [(ngModel)]="searchQuery"
      [ngModelOptions]="{standalone: true}"
      [showCancelButton]="activeSearch"
      (ionCancel)="clearSearch($event)"
      (ionInput)="menuFocusMode($event)">
      </ion-searchbar>
    </form>
  </ion-navbar>
</ion-header>

#2

My solution was to bind a function to the ionInput event, adding a custom class name…

  menuFocusMode(ev){
    let el=document.getElementsByTagName('ion-searchbar');
    el[0].classList.add('MY-CUSTOM-CLASS')
  }

… then update the scss file for my page template…

  .searchbar-ios.searchbar-show-cancel.MY-CUSTOM-CLASS .searchbar-ios-cancel {
    display: block;
    padding-left:8px;
  }

This is useful for my needs, since my search results bring up a custom UI, meaning the input field loses focus as soon as the user starts interacting with buttons (which normally causes the CANCEL button to disappear). Hope this helps someone else.


#3

Or with id :


<ion-searchbar
      placeholder="Global Search"
      [(ngModel)]="searchQuery"
      [ngModelOptions]="{standalone: true}"
      [showCancelButton]="activeSearch"
      (ionCancel)="clearSearch($event)"
      (ionInput)="menuFocusMode($event)"
      id="stay-cancel"
>
      </ion-searchbar>

and in css file:

#stay-cancel{
      &.searchbar-active{
        .searchbar-ios-cancel{
          display: block;
          padding-left:8px;
        }
      }
    }