Chapter 5: Directives in Angular
Angular directives are powerful tools that let you manipulate the DOM and extend HTML behavior. This chapter focuses on both built-in directives and creating your own custom ones for dynamic and reusable UI components.
What Are Directives?
Directives are classes in Angular that allow you to attach behavior to elements in the DOM. There are three types:
- Component Directives – With templates
- Structural Directives – Change the DOM layout (e.g.,
*ngIf
,*ngFor
) - Attribute Directives – Change the appearance or behavior of elements (e.g.,
[ngClass]
)
Built-in Structural Directives
*ngIf
Used to conditionally render elements:
<div *ngIf="isLoggedIn">
Welcome back!
</div>
*ngFor
Used to loop over a collection:
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
Built-in Attribute Directive: [ngClass]
[ngClass]
lets you dynamically apply CSS classes based on conditions:
<div [ngClass]="{ 'active': isActive, 'disabled': !isActive }">
Button
</div>
Creating Custom Attribute Directive
Step 1: Create Directive
ng generate directive highlight
Step 2: Add Logic
import { Directive, ElementRef, Renderer2, HostListener } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('mouseenter') onMouseEnter() {
this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'yellow');
}
@HostListener('mouseleave') onMouseLeave() {
this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor');
}
}
This directive changes background color on mouse events. Use it like:
<p appHighlight>Hover to highlight me!</p>
Creating Custom Structural Directive
Step 1: Generate the Directive
ng generate directive unless
Step 2: Implement Structural Behavior
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appUnless]'
})
export class UnlessDirective {
constructor(private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef) {}
@Input() set appUnless(condition: boolean) {
if (!condition) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
This directive renders content only if the condition is false — opposite of *ngIf
.
<div *appUnless="isLoggedIn">
You must log in first.
</div>
Best Practices
- Use
*ngIf
and*ngFor
to conditionally render DOM elements. - Use
[ngClass]
or[ngStyle]
for dynamic styles. - Create custom directives to keep templates clean and behavior reusable.
- Prefer
Renderer2
for DOM manipulation to ensure compatibility.
Conclusion
Directives are essential to building dynamic UIs in Angular. Whether you use built-in options or create custom ones, mastering directives will elevate your frontend development skills and keep your code modular and expressive.
Next Steps
In Chapter 6, we’ll dive into Angular Pipes — a powerful way to transform and format data directly within templates.