October 17, 2016
Angular 2 use ngSwitch ngIf ngFor without additional DOM Element
Probably you want as little DOM elements as possible. You can use a ng-container
instead of a regular HTML element in order to receive reduced markup.
Example of ngSwitch:
1 2 3 4 5 6 7 8 9 10 |
<div class="wrap"> <!-- <- Dom Element--> <ng-container [ngSwitch]="type"> <!-- <- Not a Dom Element--> <ng-container *ngSwitchCase="'a'"> <!-- <- Not a Dom Element--> <some-a-component></some-a-component> <!-- <- Dom Element--> </ng-container> <!-- <- Not a Dom Element--> <ng-container *ngSwitchCase="'b'"> <!-- <- Not a Dom Element--> <some-b-component></some-b-component> <!-- <- Dom Element--> </ng-container> <!-- <- Not a Dom Element--> </ng-container> <!-- <- Not a Dom Element--> </div> <!-- <- Dom Element--> |
Example for *ngIf:
1 2 3 4 5 6 7 8 9 |
<!-- no extra DOM element: --> <ng-container *ngIf="true"> test </ng-container> <!-- with extra DOM element: --> <div *ngIf="true"> test </div> |