Skip to main content

Structural directives

Angular's structural directives are a powerful feature that manipulate the DOM by adding, removing, or manipulating elements. These directives shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements. The most commonly used structural directives in Angular are ngIf, ngFor, and ngSwitch. Let's dive into each of these:

1. ngIf

  • Usage:-- ngIf is used to conditionally include or exclude an element from the DOM based on a specified condition. If the expression evaluates to true, the element is included in the DOM; if false, the element is removed.
  • Syntax:-- *ngIf="expression"
  • Example:--
    <div *ngIf="isVisible">Visible when 'isVisible' is true</div>

2. ngFor

  • Usage:-- ngFor is a looping directive that is used to iterate over a list and render a template for each item in the list.
  • Syntax:-- *ngFor="let item of items"
  • Example:--
    <li *ngFor="let item of items">{{ item }}</li>
  • Advanced Features:--
    • Tracking:-- Use trackBy to optimize performance by helping Angular identify which items have changed, added, or removed.
    • Local Variables:-- Access to local variables like index, first, last, even, and odd.

3. ngSwitch, ngSwitchCase, and ngSwitchDefault

  • Usage:-- This set of directives is used for conditional layouts based on a switch case.
  • Syntax:--
    • *ngSwitch="expression"
    • *ngSwitchCase="value"
    • *ngSwitchDefault
  • Example:--
    <div [ngSwitch]="condition">
    <div *ngSwitchCase="'case1'">Case 1</div>
    <div *ngSwitchCase="'case2'">Case 2</div>
    <div *ngSwitchDefault>Default case</div>
    </div>

Common Characteristics of Structural Directives

  • Syntax:-- They are typically prefixed with an asterisk *, like *ngIf, which is syntactic sugar for a more verbose syntax using template tags (<ng-template>).
  • Manipulation of DOM:-- Structural directives physically add or remove elements from the DOM.
  • Use of Template Elements:-- Under the hood, these directives use Angular's <ng-template> to instantiate embedded views.

Best Practices

  • Optimize Performance:-- For ngFor, use trackBy function to minimize DOM manipulations.
  • Avoid Complexity:-- Keep expressions in structural directives as simple as possible. Complex logic should be handled in component classes.
  • Use ngSwitch for Clarity:-- When you have multiple conditional views, ngSwitch is often more readable than multiple ngIf statements.