![]() |
VOOZH | about |
Structural directives in Angular 17 are a special type of directives that allow you to dynamically manipulate the DOM (Document Object Model) by adding, removing, or replacing elements based on certain conditions. These directives are prefixed with an asterisk (*) in the template syntax.
In this article, we will learn more about Structural Directive.
Table of Content
Structural directives are Angular directives that control the structure of the DOM by adding, removing, or manipulating elements based on conditions. They allow to create dynamic and interactive templates by conditionally rendering or repeating elements.
<!-- Example of *ngIf structural directive -->
<div *ngIf="condition">Conditional Content</div>
<!-- Example of *ngFor structural directive -->
<div *ngFor="let item of items">{{ item }}</div>
*ngIf allow to conditionally render elements based on the evaluation of an expression. The element is added to the DOM if the expression evaluates to true and removed if it evaluates to false.*ngFor provide iteration over lists or collections and generate multiple instances of a template element for each item in the list. ngSwitch allow to conditionally switch between multiple template options based on the evaluation of a matching expression. This is useful for implementing conditional logic and rendering different views or components.There are basically 3 built in structural directives available in Angular 17
NgIf is a structural directive in Angular used to conditionally render or remove an element from the DOM based on the evaluation of a given expression. The angular directive NgIf is used to add an element subtree for the expression's true value. The element subtree in this instance will not be added to the DOM if the "expression" value is either false or null.
@if(condition){text}Example :
Output:
NgSwitch is a structural directive in Angular used for conditional rendering of elements based on a given value. It is similar to a switch statement in programming languages.
Switch uses Case and Default . Switch uses Case keyword to define a set of possible element trees and Default is used to define default value when expression condition does not match to any element tree defined by Case. @switch is used to switch a set of directives among alternative views.
Example :
Output :
Note : In Angular 17 you can create duplicate cases.
NgFor is a structural directive in Angular used to render a template for each item in a collection. It iterates over each item in the collection and creates a new instance of the template for each item.
Syntax :
@for(i of items ; track i.name){
<li>{{i.name}}</li>
}@empty {
<li>There are no items.</li>
}
Note : In Angular 17 , the track concept has been defaulted. you must write.
Example :
Output :