How to set focus on input field automatically on page load in AngularJS ?
We can focus on any input field automatically using the angular directives. Here we create a custom directive that can auto-focus on any field in the form.
Creating a custom directive is just like creating an Angular component. To create a custom directive we have to replace @Component decorator with @Directive decorator.
- Create the Angular app to be used.
- Create a directive “AutoFocus” that handles the auto-focus of input fields. In this directive set the HTML element as focused.
- Then import this directive inside app.module.ts and add it to the provider’s list.
- Create a simple form on which we set the input field as focused on page reload. So we have created a signup form with two input fields “email” and “password” and add the directive “autofocus” to the “email” input field and then this field is auto-focus on page reload.
Syntax: Below “autofocus” inside the input field is a directive to auto-focus this input field.
<input autofocus type="email" name="email" #email="ngModel" ngModel />
So let’s create our simple custom directive “AutoFocus” that handles the input field auto-focus.
In the above code, we have created a directive “autofocus” here “autofocus” is the name/selector of this directive, and whenever we want to use this directive we have to provide the selector. We are using the angular “ngAfterViewInit” lifecycle hook that makes the element focused after view initialization.
Now we have to make sure that angular knows our newly created directive, so we have to provide it inside “app.module.ts” file.
So here we have provided “AutoFocus” directive inside “declarations” array and make sure to import it as well.
Now we have to create an input field on which we are going to apply this autofocus directive. For this, we have created a simple signup form and in this form user, the email input field is auto-focus on page reload.
<input autofocus type="email" matInput name="email" #email="ngModel" ngModel />
So in the above form “autofocus” directive is provided in the email input field and this field is auto-focused on page reload.