Controlling DOM Structure with Structural Directives in Angular

Learn to use the most important structural directives in Angular: '*ngIf' for conditionally rendering elements and '*ngFor' for iterating over collections and displaying data lists dynamically. Understand how these directives modify the DOM structure of your application.

🏗️

Welcome! Let's learn how to dynamically change our web page's structure with Angular.

/* Preparing the DOM... */

*ngIf: Conditional Rendering

The *ngIf directive is your tool for conditional rendering. It adds or removes an element from the DOM based on whether an expression is `true` or `false`. It's perfect for showing login/logout buttons, alert messages, or any content that depends on a specific condition.

*ngFor: Repeating Elements

The *ngFor directive is used to repeat a portion of the HTML template for each item in a collection (like an array). It's the foundation for displaying lists of data, such as a list of products, users, or comments. You can also get the index and other useful variables during the iteration.

The Magic of the Asterisk (*)

The asterisk (*) is syntactic sugar. Behind the scenes, Angular transforms a structural directive into a <ng-template> element. For example, <div *ngIf="cond"> becomes <ng-template [ngIf]="cond"><div>...</div></ng-template>. Understanding this helps in more advanced scenarios.

Common Use Cases

Use *ngIf when you need to show or hide a complete section of your UI. Use *ngFor whenever you need to render a dynamic list of items from an array or another iterable. Combining them is also common, for example, showing a message with *ngIf when an *ngFor list is empty.

Practice Zone


Interactive Test 1: Match the Directives

Drag the description to the correct directive.

Arrastra en el orden correspondiente.


Arrastra las opciones:

Shows/hides an element
Repeats elements for a list

Completa el código:

*ngIf______
*ngFor______
Unlock with Premium

Interactive Test 2: Complete the Code

Rellena los huecos en cada casilla.

<div ="isLoggedIn">Welcome!</div>

<ul>
  <li ="let user of users">
    
  </li>
</ul>
Unlock with Premium

Practice Example: Build a List

In your component, create an array of strings called `items`. Then, use *ngFor to display each item in an unordered list (`<ul>`).

* Write the code below. Correct characters will be shown in green and incorrect ones in red.

// In your component.ts items = ['First', 'Second', 'Third']; // In your component.html <ul> <li *ngFor="let item of items">{{ item }}</li> </ul>
Unlock with Premium

Knowledge Check

What does the asterisk (*) in a structural directive signify?


Unlock with Premium

Directives in a Real Angular App

In a typical Angular component, you'll find structural directives everywhere, working together to create a dynamic user experience.


1. Displaying Loading, Data, and Error States

A classic use case is managing the state of data fetched from an API. You can use `*ngIf` with an `else` clause to elegantly handle what the user sees.

<!-- Show a spinner while loading -->
<div *ngIf="isLoading">Loading...</div>

<!-- Show the data list when available -->
<ul *ngIf="data; else noData">
  <li *ngFor="let item of data">{{ item.name }}</li>
</ul>

<!-- Show a message if there's no data -->
<ng-template #noData>
  <p>No data available.</p>
</ng-template>

2. Tracking Items in *ngFor with \`trackBy\`

When the data in your \`*ngFor\` list changes, Angular has to re-render the DOM. To do this efficiently, you can provide a \`trackBy\` function. This function tells Angular how to identify a unique item, preventing it from destroying and recreating all DOM elements if only one item changes.

// In component.html
<li *ngFor="let user of users; trackBy: trackByUser">
  {{ user.name }}
</li>

// In component.ts
trackByUser(index: number, user: User): number {
  return user.id; // Unique identifier
}

Practical Takeaway: Master \`*ngIf\` and \`*ngFor\` to control your application's flow. Use \`trackBy\` with \`*ngFor\` for a significant performance boost with dynamic lists.

Structural Directives Glossary

Structural Directive
A type of Angular directive that changes the DOM layout by adding and removing DOM elements.
*ngIf
Conditionally includes a template based on the value of an expression.
*ngFor
Repeats a node for each item in a list.
<ng-template>
An Angular element that defines a template. The content is not rendered until you explicitly tell Angular to do so, which is what structural directives do internally.
Syntactic Sugar (*)
The asterisk (*) is a shorthand that simplifies the use of structural directives. Angular transforms it into a \`<ng-template>\` element during compilation.