Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
Directives are special classes in Angular that extend HTML element behavior. They allow changing DOM structure, adding styles or dynamically managing component logic.
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 |
Applied to element as attributes. They can change:
ngStyle)ngClass)<div [ngClass]="{ active: isActive }">Text</div>
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
<p appHighlight>Highlighted text</p>
Change DOM structure: add/remove elements.
<div *ngIf="isVisible">Show</div>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
*ngIf — conditional rendering.*ngFor — array iteration.*ngSwitch — multiple branching.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 />
| 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.