skip to Main Content

I have an angular page with an input field in its template.
I want to mark the text of the input field when a function is called.
when I say "mark the text" I mean (see picture below)

enter image description here

I got the element as an HTMLInputElement object with the ViewChild option, and I tried several methods like: focus, select, setSelectionRange and more…
And the result was always the same: ERROR TypeError: mailInputField.focus is not a function (not only for focus, also for the select and setSelectionRange etc…)

The input field in the template is <input #mailInputField [value]="mail">. in the .ts file the view child is: @ViewChild("mailInputField") mailInputField! : HTMLInputElement;, and my function called selectMailText() is (meanwhile) something like this.mailInputField.focus();

How can I mark this text?

2

Answers


  1. Chosen as BEST ANSWER

    Actually I found a way to do it.

    The way is: setTimeout(() => {this.mailInputField.nativeElement.select();}, 1);.

    Which means:

    1. use setTimeout for 1 milisecond so that the changes will occur after everything is fully loaded.
    2. use nativeElement and in the @ViewChild use ElementRef<HTMLInputElement> as @Loop said
    3. use (only) the select() method

  2. I think the word you are looking for is "selected" or "highlighted", not "marked"

    Check out the docs for the .select() method

    You need to .focus() and then .select()

    selectText() {
      this.mailInputField.focus();
      this.mailInputField.select();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search