tezvyn:

Angular Structural Directives: Shape Your DOM

AI-drafted, machine-checkedSource: angular.devbeginner
Angular Structural Directives: Shape Your DOM

Structural directives shape your DOM by adding, removing, or manipulating HTML elements. Use *ngIf to show/hide a block or *ngFor to loop over a list. The footgun is forgetting the asterisk (*), which is critical syntactic sugar for a more complex template.

WHY IT EXISTS: Modern web apps must display data dynamically. Hardcoding every possible UI state in HTML is impossible. Structural directives provide a clean, declarative way to connect your application's logic to the structure of the view, making the DOM a function of your state.

THE MENTAL MODEL: Think of structural directives as blueprints for your HTML. They aren't elements themselves, but instructions that tell Angular how to build or tear down parts of the DOM. An *ngIf="false" doesn't just hide an element with CSS; it completely removes it from the DOM, and an *ngIf="true" creates it from scratch.

HOW IT WORKS: The asterisk (*) is syntactic sugar that tells Angular to transform the host element. Angular wraps the element in an <ng-template> tag and then uses that template to create or destroy embedded views based on the directive's logic. For example, *ngFor="let item of items" takes its host element, puts it inside a template, and then stamps out a new copy of that template for each item in the items array.

WHEN TO USE IT: Use them whenever you need to conditionally render a part of your UI (*ngIf), repeat a block of HTML for a list of data (*ngFor), or choose between different UI blocks (*ngSwitch). They are fundamental for building almost any non-trivial Angular component.

WHEN NOT TO USE IT: Avoid structural directives if you only need to change an element's style or properties without adding or removing it from the DOM. For that, use attribute directives or property binding. For instance, to hide an element but keep it in the DOM, binding to the [hidden] property is better than *ngIf.

ONE CANONICAL EXAMPLE: To display a list of user names, you would write: <li *ngFor="let user of users">{{ user.name }}</li>. If the 'users' array contains three objects, Angular generates three <li> elements, each populated with a user's name. If the array is empty, no <li> elements are rendered at all.

Read the original → angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.