Ion-input select all text on focus

I’d like to select all text in an ion-input when focused. clearOnEdit attribute should do it but that doesn’t work either.

<ion-input #qtyInput type="number" [(ngModel)]="qty" step="0.1" clearOnEdit="true"></ion-input>

this.qtyInput.setFocus();
//this.qtyInput.select(); <- how can I make this happen?
2 Likes

@perriert Hi buddy, did you ever get input to select all text on focus? Do you mind sharing the solution if yes.

@karvanj I had to go into an other direction but not because of this problem. I haven’t tried but I think something like this should work (ViewChild):

@ViewChild('qtyInput') qtyInput;
this.qtyInput.nativeElement.select();

Alternatively you can reach all native elements on the page with ElementRef:

constructor(private projectUsersEl:ElementRef)
let el = this.projectUsersEl.nativeElement.querySelector('ng-select#usersSelectionControl');
el.children[0].click();

The methods above are not recommended!

1 Like

Just thought I would give my input (for what it is worth), I achieved this by hooking up to the click event. In fact, I went as far as creating a directive for it:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'ion-searchbar[select-all],ion-input[select-all]'
})
export class SelectAll {

  constructor(private el: ElementRef) {
  }

  @HostListener('click')
  selectAll() {
    // access to the native input element
    let nativeEl: HTMLInputElement = this.el.nativeElement.querySelector('input');

    if (nativeEl) {
      if (nativeEl.setSelectionRange) {
        // select the text from start to end
        return nativeEl.setSelectionRange(0, nativeEl.value.length);
      }

      nativeEl.select();
    }
  }

}

Then you can use it as follows:

<ion-input select-all></ion-input>

Which should highlight the text upon focusing. I read a post somewhere that implied it should be on click not focus - I cannot recall why, but I will try to find it.

4 Likes