September 27, 2016
Angular: Set Focus on Element
Want to set focus on an HTML element in your Angular app? The following step-by-step tutorial shows you how to do it easily. For a live demo of the final result, see this StackBlitz.
Step-by-step
Let’s start by adding an input element and a button to our component’s template. We give the input element an ID and pass it to the method called in the button’s click event, like this:
1 2 3 4 5 6 7 8 9 10 11 |
import { Component } from '@angular/core'; @Component({ selector: 'my-app', styleUrls: [ './app.component.css' ], template: ` <input #myInput/> <button (click)="setFocus('myInput')">Focus Input</button> ` }) export class AppComponent {} |
Now we can access the input element in our component’s code and call the .focus() method on its native element, like the following code snippet shows. Therefore, we need to make sure to have imported ViewChild and ElementRef.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Component, ElementRef, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', styleUrls: [ './app.component.css' ], template: ` <input #myInput/> <button (click)="setFocus('myInput')">Focus Input</button> ` }) export class AppComponent { @ViewChild('myInput') myInput: ElementRef; setFocus() { this.myInput.nativeElement.focus(); } } |
Our mechanism will work already, so we’re almost done. However, we should optimize our code for rendering anywhere else than in the browser: So as the last step, we’re going to consume the platformId by injecting it in our component’s constructor and adding an if statement to our setFocus() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { Component, ElementRef, Inject, PLATFORM_ID, ViewChild } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'my-app', styleUrls: [ './app.component.css' ], template: ` <input #myInput/> <button (click)="setFocus('myInput')">Focus Input</button> ` }) export class AppComponent { @ViewChild('myInput') myInput: ElementRef; constructor(@Inject(PLATFORM_ID) private platformId: Object) {} setFocus() { if (isPlatformBrowser(this.platformId)) { this.myInput.nativeElement.focus(); } } } |
That’s all! We can now trigger the focus state on our input element by clicking the button.
Thank you your example helped me 🙂
But it works for only 1 field. What if you have more text fields and you want to set focus to anyone that is empty
Salman, this enables you to set the text cursor to the wished input field. You can’t set multiple cursors in browsers.
You are looking for validation. Set the style with css classes dependent on the fields input-length.
realy nice idea.
I test it, and it’s quite good when you have a button to emit.
But, if you want that the focus is always on an input field when you come (back) on the form, how to do ? i try html autofocus, but no effect. any idea ?
for autofocus, i succeed with ngAfterViewChecked(){ }
Hi, I’m get an error on the focus.directives.spec
Error: src/app/focus.directive.spec.ts (5,23): Supplied parameters do not match any signature of
call target.
Have you tried this on an Ipad or other mobile devices? It doesn’t “catch” the focus” ’til you tap on the input.
Do you have an idea how to fix it?
Can’t bind to ‘focus’ since it isn’t a known property of ‘input’
It works even for dynamically generated fields using ngFor.
Thanks Dude! Awesome! Thanks for writing this article. It saved my Day.
Nice tutorial
Thank u man. You help me a lot. From: Brazil
What if I have multiple input type=”text” and I have to focus on the textbox which is empty? When I tried above example, It will go to the last textbox on which you have applied focus.
REply
Thank you for the answer, it helped me solve lot of focus issues. But, I have few scenarios where my is in different component. So, how to bring focus in such cases. Thank you in advance.