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:

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.

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:

That’s all! We can now trigger the focus state on our input element by clicking the button.

Related Posts

Can Kattwinkel
Developer at thecodecampus </>


13 responses to “Angular: Set Focus on Element”

  1. salman says:

    Thank you your example helped me 🙂

  2. salman says:

    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

    • Can Kattwinkel says:

      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.

  3. kyle says:

    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 ?

  4. Azamat says:

    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.

  5. Alice says:

    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?

  6. Sam says:

    Can’t bind to ‘focus’ since it isn’t a known property of ‘input’

  7. Jino R krishnan says:

    It works even for dynamically generated fields using ngFor.

    Thanks Dude! Awesome! Thanks for writing this article. It saved my Day.

  8. SKumarT says:

    Nice tutorial

  9. Jocsa says:

    Thank u man. You help me a lot. From: Brazil

  10. Piyush says:

    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.

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.