Reputation: 7724
How to select all the text in ion-input.
below are the method which i tried to select all the text in the textbox.
trail1:
<ion-input (tap)="selectAll($event)" type="text" />
selectAll(event){
event.target.select();
//window.document.element.select()
}
Trail2:
<ion-input (tap)="this.select()" type="text" />
Trail3:
<ion-input (tap)="this.setSelectionRange(0,value.length)" type="text" />
Trail4:
<ion-input #textbox (tap)="selectAll()" type="text" />
@ViewChild('textbox ') textbox ;
this.textbox .nativeElement.select();
Nothing is working for me.
if any other trial please let me know
Upvotes: 0
Views: 1783
Reputation: 1
I used a directive for this:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: 'ion-searchbar[select-all],ion-input[select-all]'
})
export class SelectAllDirective {
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();
}
}
}
I created a module for this directive:
import { NgModule } from '@angular/core';
import { SelectAllDirective } from './select-all.directive';
@NgModule({
declarations: [
SelectAllDirective
],
exports: [
SelectAllDirective
]
})
export class DirectivesModule { }
I imported this module in myPage and the AppModule and then, and used the directive in the html:
<ion-input select-all>...
Source Base: https://forum.ionicframework.com/t/ion-input-select-all-text-on-focus/79406/3
Upvotes: 0
Reputation: 749
I changed your first trial a little and that seems to work. Ion-Input is a wrapper around a html input element. To select all the text inside, you need to differentiate two cases: Either you clicked/tapped on the inner html input directly, then you can use select()
directly on the target, or you clicked/tapped on outer ion-input wrapper, then you need to access the child input first. Something like this.
<ion-input (tap)="select($event)"></ion-input>
select(event: any) {
if (event.target.select) { // tapped directly on html input
event.target.select();
} else if (event.target.children[0].select) { // tapped on the wrapper
event.target.children[0].select();
}
}
Upvotes: 2