Skip to main content
Directives are classes that add behavior to elements in your Angular applications. Angular has three types of directives: components (directives with templates), structural directives, and attribute directives.

Types of Directives

Components

Directives with templates

Structural

Change DOM layout (add/remove elements)

Attribute

Change appearance or behavior of elements

Built-in Structural Directives

Modern Angular uses built-in control flow (@if, @for, @switch) instead of structural directives. These are still available for compatibility.

*ngIf (Legacy)

*ngFor (Legacy)

*ngSwitch (Legacy)

Built-in Attribute Directives

ngClass

Dynamically add/remove CSS classes:

ngStyle

Dynamically set inline styles:

ngModel

Two-way data binding for form inputs:

Custom Attribute Directive

Create your own attribute directive:

Custom Structural Directive

Create a custom structural directive:

Directive with Multiple Inputs

Host Bindings and Listeners

Use host metadata for cleaner directives:
Modern Angular prefers using the host metadata object over @HostBinding and @HostListener decorators.

Directive Composition

Apply multiple directives to a single host:

Best Practices

  1. Use modern control flow - Prefer @if, @for, @switch over *ngIf, *ngFor, *ngSwitch
  2. Keep directives focused - Single responsibility
  3. Use host metadata - Instead of @HostBinding and @HostListener
  4. Make directives standalone - Better tree-shaking
  5. Provide meaningful selectors - Use attribute selectors with a prefix
  6. Document behavior - Clear documentation for custom directives

Next Steps

Templates

Learn template syntax and bindings

Components

Understand component architecture