Angular - Structural Directives



What are Structural Directives?

Structural directives change the structure of DOM by adding or removing elements at runtime. This type of Angular Directive is used to show or hide elements based on user authentication, render dynamic lists from APIs, or create interfaces like tabs and accordions that change based on user actions.

The structural directives are applied to elements by prefixing the directive name with an asterisk (*) symbol. To use these directives in your angular application, importing CommonModule is necessary as they are part of this module.

Built-in Structural Directives

The list of commonly used structural directives are −

  • ngIf: This directive is used to display or hide data in your application. When the given condition becomes TRUE, it will display the data, otherwise, it will not.

  • ngFor: ngFor is used to repeat a portion of elements from the given list of items.

  • ngSwitch: It checks multiple conditions.

structural directives

The ngIf Directive

The Angular Template does not provide the facility of conditional logic. Therefore, the ngIf directive is used to apply conditional logic. For this reason, it is also known as a conditional directive. For example, you can use the ngIf directive to display or hide data in your application based on the specified condition.

Example

Let us try the ngIf directive in our directive-app application to show and hide information.

Step 1: Add the below code in app.component.html.

<div *ngIf="showData">
  Tutorialspoint
</div>
<button (click) = "show()">Show Data</button>
<router-outlet />

Step 2: Import the CommonModule and add a show() method in the app.component.ts file as follows −

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'directive-app';
  showData = false; 
  show() { 
    this.showData = !this.showData; 
  }
}

Step 3: Open app.component.css file and add below CSS:

div {
    background-color: black;
    color: white;
    width: 200px;
    height: 200px;
    border-radius: 5px;
    box-shadow: 0px 5px 15px rgb(6, 51, 51);
    text-align: center;
    align-items: center;
    justify-content: center;
    display: flex;
}
button {
    border-radius: 3px;
    margin: 10px auto;
    padding: 10px 10px;
    color: white;
    font-weight: bold;
    background-color: rgb(66, 59, 59);
    cursor: pointer;
}

Now, run your application using the ng serve command and you can see the below response −

NgServe

Clicking on the button will show the hidden contents.

The ngIfElse Directive

The ngIfElse directive functions similarly to ngIf, but it also allows you to render content when the condition is evaluated as false. It is identical to the if-else condition that you may have learned in programming languages like C, C++ and Java.

Example

Let's understand how the ngIfElse works by creating a sample application.

Step 1: Add the following code in app.component.html file as follows −

<div *ngIf="showData; else noData">
  Tutorialspoint
</div>
<ng-template #noData>Nothing to display here!!</ng-template>
<button (click) = "show()">Show Data</button>

If the condition is false, a text will be displayed and in the case of TRUE, a box will be displayed.

Step 2: Finally, start your application (if not done already) using the below command −

ng serve

Now, run your application and you can see the below response −

NgApplication

The ngFor Directive

Angular template does not have the feature of looping logic as well. So, to loop through given data, Angular provides NgFor directive. For example, you can use this directive to loop over an array of items and show it as a list, gallery, table, etc.

Example

Let's understand how ngFor with the help of a sample application.

Step 1: Add the list in app.component.ts file as shown below −

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'directive-app';
  list = [1,2,3,4,5];
}

Step 2: Add ngFor directive in app.component.html as shown below −

<h2>ngFor directive Example</h2> 
<ul> 
   <li *ngFor="let l of list">
      {{l}} 
   </li>
</ul>

Here, the let keyword creates a local variable and it can be referenced anywhere in your template. The l creates a template local variable to get the list elements.

Step 3: Finally, start your application using the below command −

ng serve

The following response will be displayed −

NgFor directive

Special Case: trackBy Function

Sometimes, the ngFor directive performance is low with large lists. For example, when adding a new item or removing any item in the list may trigger several DOM manipulations. To iterate over a large object collection, we usethe trackBy function.

It tracks when elements are added or removed. It has two arguments index and element. The index is used to identify each element uniquely.

Example

Let's understand how trackBy is used with ngFor in this example.

Step 1: Add the below code in app.component.ts file.

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'directive-app';
  studentArr: any[] = [ { 
    "id": 1, 
    "name": "student1" 
 }, 
 { 
    "id": 2,
    "name": "student2" 
 }, 
 { 
    "id": 3, "name": "student3"
 },
 { 
    "id": 4, 
    "name": "student4" 
 } 
 ]; 
 trackByData(index:number, studentArr:any): number { 
    return studentArr.id; 
 }
}

Here,

We have created,

trackByData()

method to access each student element in a unique way based on the id.

Step 2: Add the below code in app.component.html file to define trackBy method inside ngFor.

<ul> 
   <li *ngFor="let std of studentArr; trackBy: trackByData">
      {{std.name}} 
   </li>
</ul>

Step 3: Now, run your application using ng serve command and you will get the below response −

NgFor with trackBy function

Here, the application will print the student names. Now, the application is tracking student objects using the student id instead of object references. So, DOM elements are not affected.

The ngSwitch Directive

Angular template does not have switch statement as well. At the place of switch statement, Angular provides the ngSwitch and its related directive to check multiple conditions and select any one of the item in a collection (of items).

Example

Let us try ngSwitch directive in our directive-app application.

Step 1: Add the following code in app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, CommonModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent implements OnInit {
  ngOnInit(): void {
    // code
  }
  title = 'directive-app';
  logInName = 'admin'; 
}

Step 2: Add the following code in app.component.html file as follows −

<h2>ngSwitch directive</h2> 
<ul [ngSwitch]="logInName"> 
   <li *ngSwitchCase="'user'"> 
      <p>User is logged in..</p> 
   </li> 
   <li *ngSwitchCase="'admin'"> 
      <p>admin is logged in</p> 
   </li> 
   <li *ngSwitchDefault> 
      <p>Please choose login name</p> 
   </li> 
</ul>

Step 3: Finally, start your application (if not done already) using the below command −

ng serve

Now, run your application and you can see the below response −

NgSwitch Directive

Here, we have defined logInName as admin. So, it matches the second SwitchCase and prints above admin related message.

Multiple Choice Questions on Angular Structural Directives

In this section, test your knowledge of the angular attribute directives by giving correct answers to the MCQs given below −

Q. 1 - Find the correct structural directive used for conditional rendering:

A - ngSwitch

B - ngIfElse

C - ngIf

D - All of the above

Answer : D

Explanation

The *ngIf, *ngSwitch and *ngIfElse directives are used for conditional rendering in Angular.

Q. 2 - The ngFor directive is used iterate over a collection. Is it a correct statement?

A - Yes

B - No

Answer : A

Explanation

In Angular, the *ngFor directive is used to repeat an HTML element for each item in a given list or array.

Advertisements