How to focus on a text box/html element again after user interaction in Angular?

Let’s say you want to focus on a html element as soon as user does something on your angular app.

May be you want user to fill a set of fields and then on clicking submit button bring back the focus on the first field.

How to do this?

STEP1: Declare template variable name for the html element

In the component file (.html) create a template variable name for the element you want to bring the focus on

For example:

<input #mytextbox>

STEP2: Declare a reference to the element using @ViewChild annotation

In the typescript file , refer the element using @ViewChild annotation like below:


  @ViewChild("mytextbox")
  private mytext!: ElementRef;

you create an instance for the native html element using ElementRef and annotate it as shown above.

STEP3: On user interaction call focus() method of the native element

On user interaction , for example on button click , call focus() method of the native element referred to in the typescript file:


  focus(){

    
    this.mytext.nativeElement.focus();
  }

That’s it!

Here is the typescript file I used for testing:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {


  @ViewChild("mytextbox")
  private mytext!: ElementRef;

  constructor() { }


  focus(){

    
    this.mytext.nativeElement.focus();
  }

  ngOnInit(): void {
  }

}

And here is the component file:


<br>
<br>
<input #mytextbox>

<br>
<input>

<br>
<br>
<button (click)="focus()">Focus</button>

When user clicks on Focus button focus goes to the first text box.

That’s it!


Posted

in

,

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading