askvity

What are Angular Directives?

Published in Angular Directives 3 mins read

Angular directives are classes that can add new behavior to the elements in the template or modify existing behavior. They are fundamental building blocks that allow you to extend the capabilities of HTML elements and manipulate the Document Object Model (DOM).

In essence, the primary purpose of Directives in Angular is to maneuver the DOM. This includes tasks such as adding new elements to the DOM, removing elements, or even changing the appearance of existing DOM elements based on application logic. They enable dynamic rendering and interaction within your Angular applications.

Types of Angular Directives

Angular categorizes directives into three main types, each serving a distinct purpose in template manipulation and behavior modification:

Component Directives

  • These are the most common type of directive.
  • A component is a directive with a template. They define reusable UI blocks with their own logic and view.
  • While technically a directive, components are typically discussed separately due to their central role in Angular application structure.
  • Example: <app-root>, <app-header>, <user-profile>.

Structural Directives

  • Structural directives are responsible for shaping or reshaping the DOM structure.
  • They typically add, remove, or manipulate elements based on conditions or loops.
  • They are often prefixed with an asterisk (*) in the template syntax.
  • Common Examples:
    • *ngIf: Conditionally adds or removes an element based on a boolean expression.
    • *ngFor: Repeats a section of the DOM for each item in a collection.
    • *ngSwitch: Adds or removes elements based on a switch value.

Attribute Directives

  • Attribute directives are used to change the appearance or behavior of an element, component, or another directive.
  • They interact with the DOM by changing attributes, styles, or classes.
  • They are applied as attributes to existing elements.
  • Common Examples:
    • NgClass ([ngClass]): Adds or removes CSS classes dynamically.
    • NgStyle ([ngStyle]): Sets CSS styles dynamically.
    • Custom attribute directives (e.g., a directive to change the background color of an input on focus).

Summary Table

Directive Type Purpose Example Syntax How it Works
Component Defines a UI block with template and logic <my-component> Creates custom elements with views.
Structural Manipulates DOM structure *ngIf, *ngFor Adds, removes, or repeats elements.
Attribute Modifies element appearance or behavior [ngClass], [ngStyle] Changes attributes, styles, or adds behavior.

In summary, Angular directives provide the power to dynamically control how your HTML looks and behaves, allowing for flexible and reactive user interfaces by manipulating the DOM based on your application's state and logic.

Related Articles