Custom Directives in Angular
Let's explore Custom Directives in Angular — one of the most powerful features when you want to encapsulate and reuse behavior across components!
🧱 What is a Custom Directive?
A custom directive is a class with the @Directive() decorator that allows you to attach custom behavior to elements in the DOM.
✨ Types of Custom Directives
- Attribute Directive – changes appearance/behavior of elements (
highlight,auto-focus, etc.) - Structural Directive – changes the DOM layout (
*ngIf,*ngFor, etc.)
🛠️ Create a Custom Attribute Directive Example
Let's create a directive that highlights text when hovered.
Step 1: Generate Directive
ng generate directive highlight
Step 2: Modify the Directive Code
// highlight.directive.ts
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.setHighlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.setHighlight('');
}
private setHighlight(color: string) {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', color);
}
}
Step 3: Use the Directive in Template
<p appHighlight>
Hover over me to see the highlight directive in action!
</p>
🧠Key Concepts
| Concept | Description |
|---|---|
@Directive() |
Declares a directive class |
ElementRef |
Reference to the host DOM element |
Renderer2 |
Safely manipulates DOM (recommended over direct access) |
@HostListener |
Listens to DOM events on the host element |
Comments
Post a Comment