Structural Directives in Angular
Structural directives are responsible for the Structure and Layout of the DOM Element. It is used to hide or display the things on the DOM. Structural Directives can be easily identified using the ‘*’. Every Structural Directive is preceded by a ‘*’ symbol.
Some of the Build in Structural Directives with Examples are as follows:
ngIf is used to display or hide the DOM Element based on the expression value assigned to it. The expression value may be either true or false.
<div *ngIf="boolean"> </div>
In the above Syntax, boolean stands for either true or false value. Hence, it leads to 2 valid syntaxes as below :
<div *ngIf="true"> </div> <div *ngIf="false"> </div>
Example of *ngIf:
ngIf-else works like a simple If-else statement, wherein if the condition is true then ‘If’ DOM element is rendered, else the other DOM Element is rendered. Angular uses ng-template with element selector in order to display the else section on DOM.
<div *ngIf="boolean; else id_selector"> </div> <ng-template #id_selector> </ng-template>
In the above Syntax, boolean stands for either true or false value. If the boolean value is true then Element in If is rendered on the DOM, else another element is rendered on the DOM .
Example of *ngIf- else:
*ngFor is used to loop through the dynamic lists in the DOM. Simply, it is used to build data presentation lists and tables in HTML DOM.
<div *ngFor="let item of item-list"> </div>
Example of *ngFor:
Consider that you are having a list as shown below:
items = ["GfG 1", "GfG 2", "GfG 3", "GfG 4"];
Example-2 of *ngFor with Indexes:
Consider that you are having a list as shown below :
items = ["GfG ", "GfG ", "GfG ", "GfG "];
Here, the index starts from ‘0’ and not ‘1’
4. *ngSwitch :
ngSwitch is used to choose between multiple case statements defined by the expressions inside the *ngSwitchCase and display on the DOM Element according to that. If no expression is matched, the default case DOM Element is displayed.
<div [ngSwitch]="expression"> <div *ngSwitchCase="expression_1"></div> <div *ngSwitchCase="expression_2"></div> <div *ngSwitchDefault></div> </div>
In the above syntax, the expression is checked with each case and then the case matching with the expression is rendered on DOM else the Default case is rendered on the DOM.
Example of *ngSwitch:
In the above example, the expression ‘one’ in ngSwitch is matched to the expression in ngSwitchCase. Hence, the Element displayed on DOM is ” One is Displayed “.