What Are Angular Directives? Types, Examples & Best Practices
Estimated study time: 10 minutes. How Angular lets you extend and manipulate the DOM beyond plain HTML.
A directive is a class that adds behavior to an element in the DOM. Components are technically directives with a template, but Angular also has two other directive types built for different jobs.
1. Component Directives
Every Angular component is a directive with its own template — the most common type you'll write day to day.
2. Structural Directives
Change the structure of the DOM by adding, removing, or repeating elements. Recognizable by the leading asterisk.
<div *ngIf="isLoggedIn">Welcome back!</div>
<li *ngFor="let item of items; trackBy: trackById">
{{ item.name }}
</li>
<div [ngSwitch]="userRole">
<p *ngSwitchCase="'admin'">Admin Panel</p>
<p *ngSwitchDefault>Standard User</p>
</div>
3. Attribute Directives
Change the appearance or behavior of an existing element without altering the DOM structure.
<p [ngClass]="{ 'highlight': isActive }">Status text</p>
<div [ngStyle]="{ color: textColor }">Styled text</div>
Writing a Custom Attribute Directive
@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
this.el.nativeElement.style.backgroundColor = '#FFF1EC';
}
@HostListener('mouseleave') onMouseLeave() {
this.el.nativeElement.style.backgroundColor = '';
}
}
Best Practices
- Prefer built-in directives (
ngIf,ngFor,ngClass) before writing a custom one. - Keep custom directives focused on one behavior — don't let them grow into mini-components.
- Always add
trackByto*ngForover dynamic lists to avoid unnecessary re-renders.
💡 Tip: If a directive starts needing its own template or complex internal state, it's usually a sign it should be a component instead.