Example autofocus directive angular 4. In Angular, using autofocus attribute unlike html5/javascript code in general. You need to create a directive first so that the code work well. This short tutorial I will share how to build and use autofocus directive in angular 4. Let’s see.
Read another article: Simple Login Form Angular 4 Tutorial For Beginner
Table of Contents
What is auto focus attribute?
According to w3schools.com, the autofocus attribute html5 is a boolean attribute. How it works is when the page loaded, then automatically focus on element. The use of the html5 autofocus attribute is as follows.
1 | <input type="text" name="names" autofocus> |
The problem is when you move the one to another pages using the angular router on single page application. Autofocus html5 only runs when the first time page loads. Unlike the SPA, all scripts loaded the first time. When we move pages, autofocus angular 4 on certain input elements will not work properly
Using native javascript, you can focus on the input field with the following commands
1 | document.getElementById("myTextField").focus(); |
Angular 4 cannot apply the above function directly although angular is javascript framework.
You need a directive so that the focus function to work properly in angular.
Autofocus Directive in Certain Elements Angular 4
Create a new angular project using Angular cli
1 | ng new testfocus |
create a new directive with the name “autofocus” using the following command
1 | ng g directive autofocus |
Then edit autofocus.directive.ts and copy the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { Directive,Input, ElementRef, Renderer } from '@angular/core'; @Directive({ selector: '[appAutofocus]' }) export class AutofocusDirective { @Input() appAutofocus: boolean; private el: any; constructor( private elementRef:ElementRef, ) { this.el = this.elementRef.nativeElement; } ngOnInit(){ this.el.focus(); } } |
Create two components to test the directive script. We need two components to move from one page to another so that directive performance can be seen.
Create a home component using the following script
1 | ng g component home |
Create a test component using the following script
1 | ng g component test |
Edit test.component.html and copy the following script
1 2 3 4 5 6 7 8 9 10 11 12 | <div> <label for="input1" input1>Input 1</label> <input type="text" #input1> </div> <div> <label for="input2" >Input 2</label> <input type="text" #input2> </div> <div> <label for="input3">Input 3</label> <input type="text" appAutofocus #input3> </div> |
A brief description:
In this example, i putt appAutoFocus directive in the input boxes number 3
Create an angular routing with app.routing.ts name and copy the following code
1 2 3 4 5 6 7 8 9 10 11 12 | import {NgModule } from '@angular/core'; import {RouterModule, Routes } from '@angular/router'; import {HomeComponent} from './home/home.component'; import {TestComponent} from './test/test.component'; const appRoutes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'test', component: TestComponent}, { path: '**', redirectTo: '/home' } ]; export const routing = RouterModule.forRoot(appRoutes); |
Open app.component.html and copy the following code
1 2 3 4 5 6 7 8 | <!--The content below is only a placeholder and can be replaced.--> <nav> <ul class="menu"> <li class="is-active"><a routerLink="/home" routerLinkActive="active">home</a></li> <li><a routerLink="/test" routerLinkActive="active">test</a></li> </ul> </nav> <router-outlet></router-outlet> |
Run the app with the following command
1 | ng serve |
Test the above script, and make sure your apps run well like the following gif image
Little explanation:
Our focus on test.component.ts
- To use autofocus directive angular 4 as good as using autofocus html5. Add the appAutofocus attribute to the input boxes we’ll focus on.
- Make sure you have import directive on app.module.ts and run the apps.
But it would be different if we want to use the focus() function on the angular 4. In native javascript, we use the following code to autofocus on text input:
1 | document.getElementById("myTextField").focus(); |
Angular requires @Viewchild decorator to interact with elements in component templates.
For example, add the following HTML code to test.component.html:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <div> <label for="input1" input1>Input 1</label> <input type="text" #input1> </div> <div> <label for="input2" >Input 2</label> <input type="text" #input2> </div> <div> <label for="input3">Input 3</label> <input type="text" appAutofocus #input3> </div> <button (click)="focusin(1)">focusing input 1</button> <button (click)="focusin(2)" >focusing input 2</button> |
Add some code to the following test.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import { Component, OnInit,ElementRef,ViewChild } from '@angular/core'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.css'] }) export class TestComponent implements OnInit { @ViewChild('input1') focus1:ElementRef; @ViewChild('input2') focus2:ElementRef; constructor() { } ngOnInit() { } focusin(numb) { if(numb == 1) { this.focus1.nativeElement.focus(); }else{ this.focus2.nativeElement.focus(); } } } |
Run the app, make sure the app works correctly as the next gif
Read another article: Angular 4 Tutorial For Beginner With Simple App Project
If you need a complete autofocus directive file, you can download it from the following link. To open the download link, share this article through social media account using the button below.
[sociallocker id=58]
URL : https://seegatesite.com/create-autofocus-directive-angular-4-example-project-download/
Password : seegatesite.com
[/sociallocker]
The routing and AutofocusDirective failed!.
working perfectly in my project. Whould you show to me the error message?