Angular Structural Directives: *ngIf, *ngFor, and *ngSwitch

2 min read

Structural directives in Angular modify the DOM by adding or removing elements based on conditions or data. Let’s explore the three most commonly used ones: *ngIf
, *ngFor
, and *ngSwitch
What are Structural Directives?
Structural directives dynamically control the layout of the DOM. They’re marked with an asterisk (*
) and include directives like *ngIf
, *ngFor
, and *ngSwitch
.
*ngIf
- Conditional Rendering
*ngIf
conditionally displays an element based on a Boolean expression.
Example
<div class="container">
<div class="row row-cols-2 row-cols-lg-2">
<div class="col">
<div *ngIf="isdiv1" class="p-3 bg-primary">Div 1</div>
</div>
<div class="col">
<div *ngIf="isToggle" class="p-3 bg-success">Div 2 </div>
</div>
</div>
<div class="row row-cols-2 row-cols-lg-2">
<div class="col">
<button (click)="hide()" class="btn btn-danger m-3">Hide</button>
<button (click)="show()" class="btn btn-primary m-3">Show</button>
</div>
<div class="col">
<button (click)="toggle()" class="btn btn-primary m-3">Toggel</button>
</div>
</div>
</div>
Component Code
isdiv1: boolean = false;
isdiv2: boolean = false;
isToggle: boolean = true;
hide() {
this.isdiv1 = false;
}
show() {
this.isdiv1 = true;
}
toggle() {
this.isToggle = !this.isToggle;
}
*ngFor
- Looping Through Data
*ngFor
iterates over a list to display dynamic content.
Example
<div class="row row-cols-2 row-cols-lg-2">
<div class="col">
<select class="form-select" aria-label="Default select example">
<option *ngFor="let city of cityArray" value="1">{{city}}</option>
</select>
</div>
<div class="col">
<select class="form-select" aria-label="Default select example">
<option *ngFor="let state of stateArray" value="1">{{state}}</option>
</select>
</div>
</div>
Component Code
cityArray: string[] = ['Mumbai', 'pune', 'Ahmdabad', 'surat', 'delhi'];
stateArray: string[] = ['Maharasht', 'M.P', 'U.P', 'Kolkata', 'Punjab'];
*ngSwitch
- Multiple Conditional Rendering
*ngSwitch
selects one of several possible templates to display.
<div [ngSwitch]="status">
<p *ngSwitchCase="'success'">Operation Successful!</p>
<p *ngSwitchCase="'error'">An Error Occurred!</p>
<p *ngSwitchDefault>Processing...</p>
</div>
Component Code
export class AppComponent {
status = "success";
}
0
Subscribe to my newsletter
Read articles from Code Inception directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
