Angular Directives (Angular 20+): A Complete Guide

Introduction

Angular Directives allow developers to extend the behavior of HTML elements, manipulate the DOM, and create reusable UI functionality without writing repetitive code.

In this tutorial, you’ll learn what Angular directives are, how they work, the different types of directives, practical examples, how to create custom directives, best practices, and common mistakes to avoid.

What is an Angular Directive?

An Angular Directive is a class that adds behavior to HTML elements or modifies the appearance and structure of the DOM.

Unlike components, directives do not have their own templates. Instead, they enhance existing HTML elements or Angular components.

For example:


<button appHighlight>
  Save
</button>

In this example, the appHighlight directive may change the button’s background color when the user hovers over it.

Why Use Directives?

Directives provide several important benefits.

1. Code Reusability

A directive can be used in multiple components without duplicating logic.

2. Cleaner Templates

Instead of writing JavaScript inside every component, reusable behavior is placed inside a directive.

3. Better Maintainability

Updating a directive automatically updates every place where it is used.

4. Separation of Concerns

Components focus on business logic while directives focus on DOM behavior.

5. Improved User Experience

Directives can dynamically change styles, visibility, animations, and interactions.

Types of Angular Directives

Angular provides three major types of directives.

1. Component Directives

Technically, every Angular component is a directive with its own template.

Example:


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent {}

A component controls a portion of the UI.

2. Structural Directives

Structural directives change the layout of the DOM by adding or removing elements.

Common examples include:

  • @if
  • @for
  • @switch

Older Angular versions also supported:

  • *ngIf
  • *ngFor
  • *ngSwitch

Angular 20 recommends using the newer control flow syntax.

Example:


@if(isLoggedIn) {
 <h2>Welcome</h2>
}

Angular creates or removes the <h2> element depending on the condition.

3. Attribute Directives

Attribute directives modify the appearance or behavior of existing elements.

Examples include:

  • ngClass
  • ngStyle
  • Custom directives

Example:


 <p [ngClass]="{'active': isActive}">
  Angular Tutorial
</p>

The element remains in the DOM, but its appearance changes.

How Directives Work

Angular processes directives during template compilation.

📖
When Angular finds a directive:
  • It creates an instance of the directive.
  • It injects required dependencies.
  • It applies the directive’s logic.
  • The DOM updates automatically.

This process is integrated with Angular’s change detection mechanism.

Built-in Structural Directives

Using @if

Component:


isAdmin = true;

Template:


@if(isAdmin) {
   <p>Administrator Panel</p>
}

Output:

Administrator Panel

If isAdmin becomes false, Angular removes the paragraph from the DOM.

Using @for

Component:


courses = ['Angular', 'React', 'Vue'];

Template:


@for(course of courses; track course) {
    <p>{{ course }}</p>
}

Output:

Angular
React
Vue

Angular efficiently renders each item.

Using @switch

Component:


status = 'success';

Template:


@switch(status) {
  @case('success') {
    <p>Operation Successful</p>
  }
  @case('error') {
    <p>Operation Failed</p>
  }
  @default {
    <p>Unknown Status</p>
  }
}

Angular displays the matching block.

Built-in Attribute Directives

ngClass

Apply CSS classes dynamically.

Component:


isActive = true;

Template:


<p [ngClass]="{'active': isActive}">
  Angular
</p>

When isActive changes, Angular automatically updates the CSS class.

ngStyle

Apply styles dynamically.

Component:


fontSize = 24;

Template:


<p [ngStyle]="{'font-size.px': fontSize}">
  Angular Tutorial
</p>

Angular updates the style whenever fontSize changes.

Creating a Custom Directive

Angular CLI makes creating directives simple.

Generate a directive (Syntax):


ng generate directive directivesName

Example:


ng generate directive highlight

Or use the short command:


ng g d directivesName

Example:


ng g d highlight

Angular creates:


highlight.directive.ts
highlight.directive.spec.ts

Basic Custom Directive Example

Example:


import { Directive, ElementRef } from '@angular/core';
@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  constructor(private element: ElementRef) {
    this.element.nativeElement.style.backgroundColor = 'yellow';
  }
}

Usage:


<p appHighlight>
  Angular Directive Example
</p>

Output:

The paragraph receives a yellow background.

Handling Events Inside Directives

Directives often respond to user events.

Example:


import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appHover]',
  standalone: true
})
export class HoverDirective {
  constructor(private element: ElementRef) {}
  @HostListener('mouseenter')
  onmouseEnter() {
    this.element.nativeElement.style.color = 'blue';
  }
  @HostListener('mouseleave')
  onMouseLeave() {
    this.element.nativeElement.style.color = 'black';
  }
}

Usage:


<p appHover>
  Hover over me
</p>

The text color changes when the mouse enters or leaves the element.

Using HostBinding

Instead of directly manipulating the DOM, Angular recommends using @HostBinding.

Example:


import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {
  @HostBinding('style.backgroundColor')
  background = 'transparent';
  @HostListener('mouseenter')
  onEnter() {
    this.background = 'yellow';
  }
  @HostListener('mouseleave')
  onLeave() {
    this.background = 'transparent';
  }
}

This approach is cleaner and follows Angular best practices.

Standalone Directives in Angular 20+

Angular 20 encourages standalone APIs.

Example:


@Directive({
  selector: '[appHighlight]',
  standalone: true
})
export class HighlightDirective {}
Standalone components import directives directly.
@Component({
  standalone: true,
  imports: [HighlightDirective],
  template: `
 <button appHighlight>
      Save
    </button>
})
export class HomeComponent {}

No NgModule declaration is required.

Structural vs Attribute Directives

Feature Structural Directive Attribute Directive
Purpose Changes DOM layout Changes appearance or behavior
Adds or Removes Elements Yes No
Modifies Existing Element No Yes
Example @if, @for @ngClass, ngStyle
Uses Template Control Flow Yes No

Structural directives affect whether elements exist, while attribute directives affect how existing elements behave or look.

Best Practices

Follow these recommendations when creating directives.

1. Create Small Directives

Each directive should have a single responsibility.

2. Prefer HostBinding

Avoid manipulating the DOM directly whenever possible.

Instead of:


element.nativeElement.style.color = 'red';

Prefer:


@HostBinding('style.color')

3. Avoid Business Logic

Directives should focus on UI behavior.

Business logic belongs in components or services.

4. Use Meaningful Names

Good examples:

  • appHighlight
  • appTooltip
  • appPermission

Avoid vague names like:

  • appTest
  • appExample

5. Keep Directives Reusable

Avoid writing directives that only work for a single component.

Reusable directives improve maintainability.

Common Mistakes

1. Manipulating the DOM Excessively

Direct DOM manipulation may cause compatibility issues with server-side rendering.

Prefer Angular abstractions such as HostBinding and Renderer2.

2. Combining Multiple Responsibilities

Avoid creating one directive that performs styling, validation, API calls, and animations simultaneously.

Keep directives focused.

3. Forgetting Standalone Imports

Standalone directives must be imported into standalone components before use.

4. Using Structural Directives Incorrectly

Remember that structural directives modify the DOM layout, while attribute directives modify existing elements.

Choosing the wrong directive type can make your templates confusing.

Advantages and Disadvantages

Advantages

  • Encourages reusable code
  • Keeps templates clean
  • Improves maintainability
  • Extends HTML functionality
  • Reduces duplicate code
  • Integrates with Angular change detection
  • Works with standalone components
  • Supports custom DOM behavior

Disadvantages

  • Too many custom directives can make projects harder to understand
  • Direct DOM manipulation should be avoided
  • Poorly designed directives can reduce maintainability
  • Structural directives may be harder for beginners to understand

When Should You Create a Custom Directive?

📖
A custom directive is a good choice when:
  • The same UI behavior is used in multiple places.
  • You need reusable DOM manipulation.
  • You want to encapsulate styling or interaction logic.
  • The behavior is independent of business logic.
  • Existing Angular directives don’t meet your requirements.

If the functionality involves complex business rules, API calls, or application state, consider using a service instead of a directive.

Conclusion

Angular Directives are one of the framework’s most powerful features, enabling developers to extend HTML, manipulate the DOM, and create reusable UI behavior with minimal effort.

Whether you’re conditionally displaying content using structural directives like @if and @for, dynamically applying styles with attribute directives such as ngClass and ngStyle, or building your own custom directives, they help keep applications modular, maintainable, and easy to understand.

Angular Directive – Objective Questions (MCQs)

Q1. Directive is used to:






Q2. How many types of directives exist?






Q3. Which is NOT a directive type?






Q4. ngIf is a:






Q5. Directives are written using:






Related Angular Tutorials