This week's giveaway is in the Beginning Java forum.
We're giving away four copies of Bad Programming Practices 101 (e-book) and have Karl Beecher on-line!
See this thread for details.
Win a copy of Bad Programming Practices 101 (e-book) this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to programmatically manage focus in an Angular 2 app?  RSS feed

 
Ranch Hand
Posts: 90
1
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For accessibility purposes, I sometimes need to move the focus to certain elements. What is the Angular way of focusing a component?

Related to this, how do I make a custom component focusable by adding an appropriate tabindex? Is there a framework-wide system for obtaining tabindex values and customizing tab order?
 
Author
Greenhorn
Posts: 7
5
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Approach #1

For simple scenarios when the element that should get the focus is always the same, for example first input field on the form, you can handle it with pure HTML - autofocus attribute.

Approach #2

For more complex scenarios when the element is dynamically determined based on the data or user's behavior, you can use @ViewChild() directive to query an element in the template and call focus() method for the element, here is a quick example:

Template:

Component:


A more complex example would use renderer API to avoid tight coupling to the browser platform:

Component:


The code above will work even outside of the browser for example if you pre-render your page on the server-side with Angular Universal.

Approach #3

And finally the more advanced technique would be to create a custom reusable directive that will focus the element if you pass it the true value. Here is how you would use it in a template:



Here is a straightforward implementation of myFocus directive:




As of your second question it's a broad one, it depends on your particular task. The general advice would to define a tabindex on your custom component and pass its value through to the underlying native input element. As of the group of components you can take a look at Angular Material's FocusTrap directive. There is a corresponding spec file that shows how it's supposed to be used.
 
You can't expect to wield supreme executive power just because
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!