Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Angular FAQ: Top Questions

16. What is a Structural Directive in Angular?

In Angular, structural directives are special directives that alter the structure of the DOM by adding, removing, or manipulating elements. These directives are typically prefixed with an asterisk * and are responsible for shaping how Angular renders content conditionally or repetitively in the template.

Unlike attribute directives (which change the appearance or behavior of existing elements), structural directives modify the DOM layout. They dynamically control which HTML elements appear based on logic in the component.

  • Syntax and Convention:
    • Structural directives use shorthand syntax like *ngIf and *ngFor, which Angular desugars into an extended <ng-template> representation under the hood.
    • Example: <div *ngIf="condition"> is equivalent to placing a directive on an <ng-template> element.
  • Common Structural Directives:
    • *ngIf – Conditionally includes a template block when the expression evaluates to true.
    • *ngFor – Iterates over a collection and renders a template for each item.
    • *ngSwitch – Conditionally switches among multiple templates using ngSwitchCase and ngSwitchDefault.
  • Custom Structural Directives:
    • Developers can create their own structural directives by manipulating the view using ViewContainerRef and TemplateRef.
    • These custom directives follow the same Angular lifecycle and can enable advanced layout control.

// app.component.ts

export class AppComponent {
  isLoggedIn = true;
  items = ['Angular', 'React', 'Vue'];
}
        

// app.component.html

<div *ngIf="isLoggedIn">Welcome, User!</div>

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

Explanation of the Example Code:

  • The *ngIf="isLoggedIn" directive conditionally includes the welcome message only when isLoggedIn is true.
  • The *ngFor directive iterates over the items array and creates a list item <li> for each value.
  • Both directives modify the DOM structure at runtime depending on data or logic defined in the component class.

Structural directives are powerful tools for building dynamic UIs in Angular, allowing developers to declaratively control what gets rendered based on component state or data collections.