
Angular Structural Directives with Examples
An Structural directive changes the DOM layout by adding and removing DOM elements.
Structural directives are responsible for HTML layout manipulation . They change the DOM’s structure, typically by adding, removing, or manipulating elements.
Angular provide us some built-in structural directives such as ngIf, ngFor, and ngSwitch.
Structural directive can directly apply on to the host element. Structural directives are easy to recognize with an asterisk (*) precedes, like
1 |
<div *ngIf="country">{{country.name}}</div> |
1. Examples of *ngIF :
1 2 |
<span *ngIf="success">Added to Wishlist</span> <span *ngIf="!success">Not Added to wishlist</span> |
2. Examples of *ngFor:
1 2 3 |
<ul> <li *ngFor = "let hero of Heros"> {{ hreo }}</li> </ul> |
3. Examples of *ngSwitch:
1 2 3 4 5 6 7 |
<div [ngSwitch] = "switchVar"> <div *ngSwitchCase = "'1'">Switch 1 </div> <div *ngSwitchCase = "'2'">Switch 2 </div> <div *ngSwitchCase = "'3'">Switch 3 </div> <div *ngSwitchCase = "'4'">Switch 4 </div> <div *ngSwitchDefault>Switch Default </div> </div> |
Now Understanding the asterisk(*), what is does:
consider the following example, whenever angular seen the asterisk(*) symbols, it generate an template tag, and wrap that element in to it. Angular transform the ngIf to be a property binding. This all happened at the run time or can say behind the scene.