December 20, 2023 05:50 by
Peter
We will discover how to create a custom autofocus directive in an Angular application in this tutorial.
Required conditions
Basic familiarity with Angular 2 or later; installation of Node and NPM; Visual Studio Code; Bootstrap (Optional)
Make an Angular Project
The command to create an Angular project is as follows.
ng new angapp
Now install Bootstrap by using the following command,
npm install bootstrap --save
Now open the styles.css file and add Bootstrap file reference. To add a reference in the styles.css file add this line.
@import '~bootstrap/dist/css/bootstrap.min.css';
Create Directive
Create a new directive using the Angular CLI command
ng generate directive autofocus
Now open autofocus.directive.ts file and add following code
import { Directive, ElementRef, AfterViewInit } from '@angular/core';
@Directive({
selector: '[Autofocus]'
})
export class AutofocusDirective implements AfterViewInit {
constructor(private el: ElementRef) {}
ngAfterViewInit() {
this.el.nativeElement.focus();
}
}
Now open app.component.html file and add the following code.
<div class="container" style="margin-top:10px;margin-bottom: 24px;">
<div class="col-sm-12 btn btn-info">
Autofocus Directive in Angular Application
</div>
</div>
<div class="container">
<input type="text" class="form-control" placeholder="Auto Focused Textbox" Autofocus />
</div>
Now open app.module.ts and following code
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AutofocusDirective } from './autofocus.directive';
@NgModule({
declarations: [
AppComponent, AutofocusDirective
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule { }
Now run the application using npm start and check the result.
We discovered how to make a personalized autofocus directive in an Angular application by reading this post.