Angular Directives
Imagine you have a magic wand that can change the appearance or behavior of any object with a wave. In Angular, directives are exactly that – they allow you to attach custom behavior to elements in the DOM (Document Object Model).
Directives are classes that add additional behavior to elements. Angular has three types of directives:
- Components – Directives with a template. The most common directive.
- Structural Directives – Change the DOM layout by adding or removing elements (e.g., *ngIf, *ngFor).
- Attribute Directives – Change the appearance or behavior of an element (e.g., ngClass, ngStyle).
Here's a simple custom attribute directive that changes background color on hover:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
Use it in a template:
<p appHighlight>Hover me to see the magic!</p>
Two Minute Drill
- Directives add behavior to DOM elements.
- Three types: Components (with templates), Structural (*ngIf, *ngFor), Attribute (ngClass, ngStyle).
- Use @Directive decorator to create custom directives.
- ElementRef gives access to the DOM element.
- HostListener listens to events on the host element.
Need more clarification?
Drop us an email at career@quipoinfotech.com
