Search code examples
ionic-frameworkionic2searchbar

Ionic2 select text in ion-searchbar


In an ion-input focus event we can select all the text like this

<ion-input (focus)="selectAll($event)></ion-input>

But in an ion-searchbar it does not work:

<ion-searchbar (focus)="selectAll($event)></ion-searchbar>

The selectAll() code would be:

public selectAll(event): void {
    event.target.select();
}

I have seen in ionic's Github that the input component returns a FocusEvent:

inputFocused(event) {
  this.focus.emit(event);
}

On the other hand the ion-searchbar returns a searchbar (this):

inputFocused() {
  this.focus.emit(this);

  this.isFocused = true;
  this.shouldLeftAlign = true;
  this.setElementLeft();
}

Why does it not return a FocusEvent too? How can we select all the text in an ion-searchbar when it is focused?

Thank you


Solution

  • The ion-searchbar is more than just an input element. Therefore you need to grab the inputElement attribute instead of the target:

    public selectAll(event): void {
        event.inputElement.select();
    }