0
0
AngularConceptBeginner · 3 min read

What Are Directives in Angular: Simple Explanation and Examples

In Angular, directives are special instructions in the HTML that tell Angular to do something with the DOM, like changing its appearance or behavior. They let you create reusable components or add custom behavior to elements easily.
⚙️

How It Works

Think of directives as helpers that tell Angular how to change or control parts of your webpage. Just like a traffic sign guides drivers, directives guide Angular on what to do with HTML elements.

There are three main types: components (which are directives with a template), attribute directives (which change the look or behavior of an element), and structural directives (which change the layout by adding or removing elements). Angular reads these directives and updates the page automatically.

💻

Example

This example shows a simple attribute directive that changes the background color of a button when you hover over it.

typescript
import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appHoverHighlight]'
})
export class HoverHighlightDirective {
  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
  }

  private highlight(color: string | null) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

// Usage in a component template:
// <button appHoverHighlight>Hover me!</button>
Output
A button that changes its background color to yellow when hovered and returns to normal when the mouse leaves.
🎯

When to Use

Use directives when you want to add reusable behavior or appearance changes to HTML elements without repeating code. For example, you can create a directive to format dates, validate input fields, or show/hide elements based on conditions.

Structural directives are great when you want to add or remove parts of the page dynamically, like showing a list only if it has items. Attribute directives help when you want to change styles or behavior, like highlighting text or disabling buttons.

Key Points

  • Directives are instructions that tell Angular how to modify the DOM.
  • There are three types: components, attribute directives, and structural directives.
  • They help keep your code clean by reusing behavior across your app.
  • Attribute directives change element appearance or behavior.
  • Structural directives change the layout by adding or removing elements.

Key Takeaways

Directives let Angular modify HTML elements to add behavior or change appearance.
Use attribute directives to change styles or behavior of elements.
Use structural directives to add or remove elements dynamically.
Components are a special kind of directive with their own templates.
Directives help you write reusable and clean code in Angular apps.