How to Create a Simple Directive in Angular
Jacob Naryan - Full-Stack Developer
Posted: Sat Jul 22 2023
Last updated: Wed Nov 22 2023
Angular provides several core decorators that allow us to create more efficient and manageable code. One of these is the @Directive decorator. This blog post will guide you on how to use this decorator effectively. As an example, we’ll create a simple directive that changes the background color of an element.
1. What is a Directive?
Before we begin, it’s crucial to understand what a directive is. In Angular, a directive is a class with a @Directive decorator. Directives let you invent new HTML syntax and are useful for DOM manipulation.
2. Creating a New Directive
To create a new directive, you can use Angular CLI’s generate directive command:
ng generate directive changeColor
This command will create two files: change-color.directive.ts and change-color.directive.spec.ts (for testing purposes).
3. Writing the Directive
Open the change-color.directive.ts file and you’ll see a structure like this:
import { Directive } from '@angular/core';
@Directive({
selector: '[appChangeColor]'
})
export class ChangeColorDirective {
constructor() { }
}
By using the @Directive decorator, we’ve declared ChangeColorDirective as a directive and specified its selector.
Now let’s make this directive change the background color of an element:
import { Directive, ElementRef, Renderer2 } from '@angular/core';
@Directive({
selector: '[appChangeColor]'
})
export class ChangeColorDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {
renderer.setStyle(el.nativeElement, 'background-color', 'yellow');
}
}
In this code, ElementRef grants direct access to the host DOM element through its nativeElement property. Renderer2 is used to modify this element.
4. Updating app.module.ts
After creating the directive, add it to the declarations array in the AppModule (app.module.ts):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ChangeColorDirective } from './change-color.directive';
@NgModule({
declarations: [
AppComponent,
ChangeColorDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
5. Using the Directive in HTML
Now you can use your custom directive in your HTML file like this:
<div appChangeColor>
This div's background color should be yellow.
</div>
And there you have it! You’ve just created a simple directive in Angular using the @Directive decorator that changes an element’s background color to yellow.
Thank you for reading. If you liked this blog check out more tutorials about software engineering here.