Angular 2 select text on specific input

Using jQuery, we select the entire contents of a specific input to send as follows:

<form id="target"> <input id="input-1" type="text" value="some value" /> <form> 
 $("#target").submit((event) => { event.preventDefault(); $("#input-1").select(); }); 

How to do it with Angular 2?

+14
source share
3 answers

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.

+40
source

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(); } 
+7
source

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

  1. Add local variable name
 <input type="text" #myInput (focus)="$event.target.select()" /> 
  1. Use ViewChild to 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.

0
source

Source: https://habr.com/ru/post/1264333/


All Articles