A directive in Angular is a powerful tool that allows you to manipulate the DOM (Document Object Model) or add behavior to an HTML element. Directives can be used to:
- Change the appearance of elements.
- Add event listeners.
- Modify the structure of the DOM.
Types of Directives
-
Component Directives: These are the most common and represent Angular components (they have a template, styles, and logic).
-
Structural Directives: These directives modify the structure of the DOM by adding or removing elements. For example:
*ngIf
: Conditionally includes a template based on an expression.*ngFor
: Loops over a collection and creates an instance of the template for each item.
-
Attribute Directives: These are used to alter the appearance or behavior of an element. For example:
ngClass
: Adds/removes CSS classes dynamically.ngStyle
: Applies inline styles to elements dynamically.
Custom Attribute Directive Example
Let’s go through an example where we create a custom attribute directive that changes the background color of an element when the user hovers over it.
Step-by-Step Guide
1. Generate a Custom Directive
Run the following command to generate a directive:
ng generate directive hoverBackground
This will create a new directive file hover-background.directive.ts
.
2. Create the Directive
Here’s how we can implement the custom HoverBackgroundDirective
to change the background color when an element is hovered over:
hover-background.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHoverBackground]' // The selector used in HTML
})
export class HoverBackgroundDirective {
constructor(private el: ElementRef) { }
// Listener for mouse enter event
@HostListener('mouseenter') onMouseEnter() {
this.changeBackgroundColor('yellow'); // Change background color to yellow on hover
}
// Listener for mouse leave event
@HostListener('mouseleave') onMouseLeave() {
this.changeBackgroundColor('transparent'); // Reset background color when hover ends
}
// Method to change the background color of the element
private changeBackgroundColor(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
3. Register the Directive in the Module
You need to declare and register the directive in your AppModule
so Angular can use it throughout your application.
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { HoverBackgroundDirective } from './hover-background.directive'; // Import the directive
@NgModule({
declarations: [
AppComponent,
HoverBackgroundDirective // Declare the directive here
],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
4. Use the Directive in the Template
Now, we can use the appHoverBackground
directive in any HTML element within your components.
app.component.html
<div appHoverBackground>
Hover over this box to change its background color!
</div>
Explanation of the Code:
-
Directive Decorator (
@Directive
):selector: '[appHoverBackground]'
— This defines how the directive will be applied to elements in the template. Any element with the attributeappHoverBackground
will have the directive behavior applied to it.
-
ElementRef:
- We use
ElementRef
to get a reference to the DOM element that the directive is applied to. ThenativeElement
property allows us to manipulate the element directly.
- We use
-
HostListener:
@HostListener('mouseenter')
listens for the mouse entering the element, and we change its background color to yellow.@HostListener('mouseleave')
listens for when the mouse leaves the element and resets the background color.
-
Change Background Color:
- The
changeBackgroundColor
method directly manipulates thebackgroundColor
style of the element.
- The
What Happens in the Template?
When you hover over the div
element, the background color will change to yellow. When you move your mouse away, the background color will reset to transparent.
Conclusion
In this example:
- We created a custom directive that reacts to mouse events and changes the background color of an element.
- We used
HostListener
to listen for mouse events (mouseenter
andmouseleave
). - We used
ElementRef
to directly manipulate the DOM.
This is just one simple example of how directives can be used in Angular to add custom behavior to elements. You can create more complex behavior by using Angular directives to handle events, modify styles, and even manipulate the DOM structure.