0
0
AngularConceptBeginner · 3 min read

What is Structural Directive in Angular: Explanation and Example

A structural directive in Angular changes the layout by adding or removing elements from the DOM. It controls how the HTML structure appears dynamically, like *ngIf or *ngFor.
⚙️

How It Works

A structural directive in Angular works by changing the structure of the web page. Imagine you have a box of LEGO blocks. A structural directive decides which blocks to keep and which to remove to build different shapes. It adds or removes HTML elements based on conditions or loops.

For example, if you want to show a message only when a user is logged in, a structural directive can add that message element to the page only when the condition is true. This way, the page layout changes dynamically without reloading.

💻

Example

This example uses the *ngIf structural directive to show a message only if isLoggedIn is true.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h1>Welcome to Angular Structural Directive</h1>
    <button (click)="toggleLogin()">Toggle Login</button>
    <p *ngIf="isLoggedIn">You are logged in!</p>
  `
})
export class AppComponent {
  isLoggedIn = false;

  toggleLogin() {
    this.isLoggedIn = !this.isLoggedIn;
  }
}
Output
Welcome to Angular Structural Directive [Toggle Login Button] (When isLoggedIn is true) You are logged in! (When isLoggedIn is false) No message shown
🎯

When to Use

Use structural directives when you want to change the page layout by adding or removing elements based on conditions or lists. For example:

  • Show or hide parts of the page depending on user actions or permissions.
  • Display a list of items dynamically using loops.
  • Create reusable templates that appear only when needed.

They help keep your app efficient by not rendering unnecessary elements.

Key Points

  • Structural directives change the DOM layout by adding or removing elements.
  • They use a star (*) prefix like *ngIf and *ngFor.
  • They help create dynamic and responsive user interfaces.
  • They differ from attribute directives, which only change element appearance or behavior.

Key Takeaways

Structural directives control the presence of elements in the DOM dynamically.
Use *ngIf to conditionally show or hide elements based on logic.
Use *ngFor to repeat elements for each item in a list.
They help build flexible and efficient Angular layouts.
Structural directives always start with a star (*) in the template.