What Is structural Directives in Angular?
Kirtesh Shah
Structural directives in Angular allow you to modify the DOM based on certain conditions. Here are some examples of commonly used structural directives:
*ngIf: This directive is used to conditionally add or remove elements from the DOM based on a boolean expression. For example, the following code will only show the div element if the “showElement” variable is true:
<div *ngIf="showElement">This element is only shown if showElement is true.</div>
*ngFor: This directive is used to iterate over a collection of items and create a new element for each item in the collection. For example, the following code will create a list of items based on an array of strings:
<ul> <li *ngFor="let item of items">{{ item }}</li></ul>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
*ngSwitch: This directive is used to conditionally add or remove elements from the DOM based on a switch expression. For example, the following code will show a different message depending on the value of the “status” variable:
<div [ngSwitch]="status"> <div *ngSwitchCase="'success'">Success message</div> <div *ngSwitchCase="'warning'">Warning message</div> <div *ngSwitchDefault>Error message</div></div>
<div [ngSwitch]="status">
<div *ngSwitchCase="'success'">Success message</div>
<div *ngSwitchCase="'warning'">Warning message</div>
<div *ngSwitchDefault>Error message</div>
</div>
In this example, the *ngSwitch directive checks the value of the “status” variable and shows a different message based on its value.