Angular 2 select text on specific input
You can easily do this in a template as follows:
<input type="text" (click)="$event.target.select()" /> or add a local variable to your element and link, and instead:
<input type="text" #myInput (click)="myInput.select()" /> The advantage of the second approach is that by setting a local variable name for your element, other elements can also refer to this variable.
I figured out the way without using an event listener ...
<form id="target"> <input id="input-1" #input-1 type="text" value="some value" /> <form> component.ts
@ViewChild('input-1') inputOne: ElementRef; selectInput() { const inputElem = <HTMLInputElement>this.inputOne.nativeElement; inputElem.select(); } The best idea for focus events is to use a focus event rather than a click event.
<input type="text" (focus)="$event.target.select()" /> To focus on the logic of your component, you need to add a few more things
- Add local variable name
<input type="text" #myInput (focus)="$event.target.select()" /> - Use
ViewChildto access the DOM element
@ViewChild("#myInput") myInputField: ElementRef; editMyInputField(): void { this.myInputField.nativeElement.focus(); } To start the selection programmatically from outside the component, you will need to use @Input . Sort of:
@Input() set myInputFocus() { this.editMyInputField(); } All of this should still work with Angular 8. I have not tested any of this on Angular 2 or 4.
It would be a bit more complicated if you use dynamic inputs. For such cases, I used the form as a parent link, and did not declare many local variables in the component.