What are Directives and What Types Exist in Angular?
What are Directives in Angular?
Directives are special classes in Angular that extend HTML element behavior. They allow changing DOM structure, adding styles or dynamically managing component logic.
Directive Types in Angular
Angular divides directives into three main categories:
| Type | Purpose | Examples |
|---|---|---|
| Attribute | Change element appearance or behavior | ngClass, ngStyle, customHighlight |
| Structural | Change DOM structure (add/remove elements) | ngIf, ngFor, ngSwitch |
| Custom | Directives you create for adding reusable logic | appTooltip, appValidate |
Attribute Directives
Applied to element as attributes. They can change:
- element style (
ngStyle) - class (
ngClass) - behavior through event listeners
Example: ngClass
<div [ngClass]="{ active: isActive }">Text</div>
Custom Attribute Directive Example
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
<p appHighlight>Highlighted text</p>
Structural Directives
Change DOM structure: add/remove elements.
Examples
<div *ngIf="isVisible">Show</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
*ngIf— conditional rendering.*ngFor— array iteration.*ngSwitch— multiple branching.
Creating Custom Directive
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appZoom]'
})
export class ZoomDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onEnter() {
this.el.nativeElement.style.transform = 'scale(1.1)';
}
@HostListener('mouseleave') onLeave() {
this.el.nativeElement.style.transform = 'scale(1)';
}
}
<img src="..." appZoom />
Difference from Components
| Characteristic | Directive | Component |
|---|---|---|
| Selector | [appDirective] (attribute) | <app-component> (tag) |
| Template | No | Yes |
| Usage | As behavior or style | As UI element |
Tip:
Use directives for reusable behavior that doesn't require template. If UI is needed — better create component.