Structural Directives

Overview

The second type of directive is structural directives, which allow developers to manipulate the structure of the Document Object Model (DOM) based on conditions. In this article, we will explore what structural directives are, how they work, and provide examples to fully explain their significance in Angular development.

Understanding Structural Directives

Structural directives in Angular are a category of directives that modify the structure of the DOM by adding, removing, or replacing elements based on certain conditions. They are known for their ability to control the flow of your application by rendering or removing elements dynamically. Angular provides several built-in structural directives, with two of the most commonly used ones being *ngFor and ngIf.

*ngFor - Directive: Iterating through Lists

The *ngFor directive is used to iterate over collections (arrays or lists) and generate HTML elements for each item in the collection. This makes it a fundamental tool for rendering dynamic lists.

Here's an example of using *ngFor to display a list of items:

<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>

In this example, the *ngFor directive iterates through the items array and generates list items for each element in the array.

*ngIf - Directive: Conditional Rendering

The *ngIf directive is used to conditionally render elements based on a specified condition. This is incredibly useful for showing or hiding elements in response to user interactions or data changes.

Here's an example of using *ngIf to conditionally render a message:

<p *ngIf="isLoggedIn">Welcome to our website!</p>

In this example, the paragraph will only be displayed if the isLoggedIn variable is true.

Creating Custom Structural Directives

While Angular provides prowerful built-in structural directives, developers can also create custom structural directives when specific functionality is needed. Creating custom structural directives involves defining a directive class, implementing the ng-template structure, and using the * prefix to apply the directive in templates.

Here's a simplified example of a custom structural directive that repeats content multiple times:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[appRepeatContent]'
})
export class RepeatContentDirective {
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {}

  @Input() set appRepeatContent(times: number) {
    for (let i = 0; i < times; i++) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}

In this example, the appRepeatContent directive is used to repeat the content it wraps a specified number of times.