Using Structural Directives in Templates

Tutorial 2 of 5

Using Structural Directives in Templates

1. Introduction

In this tutorial, we will explore the concept of structural directives in Angular. These directives are a powerful tool that allow us to dynamically modify the layout of our DOM by adding, removing, or manipulating elements.

Goals

  • Understand the purpose and usage of structural directives in Angular
  • Learn how to use ngIf and ngFor in your templates

Pre-requisites

  • Basic knowledge of HTML and JavaScript
  • An understanding of Angular basics would be beneficial

2. Step-by-Step Guide

Structural directives in Angular are prefixed with an asterisk () and are used to shape or reshape the DOM's structure. The two most commonly used structural directives are ngIf and *ngFor.

ngIf

The *ngIf directive serves to include or remove an element and its descendants from the DOM based on the truthy or falsy value of an expression.

ngFor

The *ngFor directive is used to loop over a collection and then render the HTML element for each item in the collection.

3. Code Examples

Example 1: Using ngIf

<p *ngIf="showParagraph">Hello, User!</p>

In this example, Angular will only render the paragraph element if the showParagraph property of the component is true. Otherwise, it removes the paragraph from the DOM.

Example 2: Using ngFor

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

In this case, Angular will create a <li> element for each item in the items array. The {{ item }} inside the <li> is an interpolation that will be replaced by the value of the current item.

4. Summary

In this tutorial, we have learned about Angular's structural directives - ngIf and ngFor, and how to use them in our templates for dynamic content rendering. These directives are an essential part of Angular and knowing how to use them effectively will greatly enhance your Angular development skills.

For further learning, I recommend exploring other structural directives in Angular such as *ngSwitch.

5. Practice Exercises

Exercise 1: Create a template that displays a list of names using *ngFor.

Solution:

<ul>
  <li *ngFor="let name of names">{{ name }}</li>
</ul>

In this solution, a <li> element is created for each name in the names array.

Exercise 2: Modify the above template to only display the names list if there's at least one name in the array using *ngIf.

Solution:

<ul *ngIf="names.length > 0">
  <li *ngFor="let name of names">{{ name }}</li>
</ul>

Here, the <ul> element will only be rendered if there's at least one name in the names array.

Remember to always experiment with what you've learned and try to apply these concepts in your Angular projects for better understanding and practice.