Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Structural Directives in Angular

Structural directives in Angular allow you to alter the DOM layout by adding or removing elements. This tutorial covers the basics of structural directives and how to use them effectively in your Angular applications.

What are Structural Directives?

Structural directives are directives that change the structure of the DOM by adding, removing, or manipulating elements. They are prefixed with an asterisk (*) to denote their structural nature.

Common Structural Directives

The most commonly used structural directives in Angular are *ngIf, *ngFor, and *ngSwitch.

*ngIf

The *ngIf directive conditionally includes or excludes elements from the DOM based on the result of an expression:

<div *ngIf="isVisible">This is conditionally visible</div>

export class AppComponent {
  isVisible = true;
}

*ngFor

The *ngFor directive iterates over a collection and renders an element for each item in the collection:

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

export class AppComponent {
  items = ['Item 1', 'Item 2', 'Item 3'];
}

*ngSwitch

The *ngSwitch directive conditionally includes or excludes a set of elements based on a switch expression:

<div [ngSwitch]="color">
  <div *ngSwitchCase="'red'">Red</div>
  <div *ngSwitchCase="'green'">Green</div>
  <div *ngSwitchCase="'blue'">Blue</div>
  <div *ngSwitchDefault>Default color</div>
</div>

export class AppComponent {
  color = 'red';
}

Creating Custom Structural Directives

You can create custom structural directives by implementing the Directive decorator and using the TemplateRef and ViewContainerRef services:

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

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

  @Input() set appUnless(condition: boolean) {
    if (!condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }
}

Using the Custom Structural Directive

<div *appUnless="isVisible">This is conditionally visible</div>

export class AppComponent {
  isVisible = false;
}

Key Points

  • Structural directives change the structure of the DOM by adding, removing, or manipulating elements.
  • Common structural directives include *ngIf, *ngFor, and *ngSwitch.
  • Custom structural directives can be created using the Directive decorator and the TemplateRef and ViewContainerRef services.
  • Structural directives are prefixed with an asterisk (*) to denote their structural nature.

Conclusion

Structural directives in Angular are powerful tools for altering the DOM layout. By understanding and using structural directives effectively, you can create more dynamic and flexible Angular applications. Happy coding!