Auto focusing to an element is one of the common requirement in client side web applications, especially when dealing with forms.
We can use autofocus attribute directly on an element, but the problem with this can be, the element will be auto focused only when we load the entire application from that page/component. In single page applications, when we navigate from one component to another component, then the browser do not trigger the auto focus on the element in the newly loaded component (this can be applied within the same component when we load certain DOM content using ngIf and if the element that we want to focus is inside the newly loaded DOM) .
To auto focus an element, we need to access that element and focus it programmatically which can be done in different ways.
In our example, we are using a simple form and wants to auto focus on the first element in the form.
If the element is directly available in the DOM, that is, if it is not conditionally rendered, then we can access this element directly inside our component ts file using ViewChild decorator.
If the element is rendered conditionally such as by using ngIf, then we may not be able to access this element when we load the component, if is it getting rendered initially. In this scenario, we can use a setter function and add ViewChild decorator to this function.
Add a wrapper div to the previous html and also a button to trigger the condition
Another way to set auto focus to an element is by creating a custom directive. We can access any element which we want to auto focus inside the directive and set it.