ng-template
The <ng-template>
is an Angular element for rendering HTML. It is never displayed directly. Use for structural directives such as: ngIf, ngFor, ngSwitch,..
Example:
<div *ngIf="hero" class="name">{{hero.name}}</div>
Angular translates the *ngIf attribute into a <ng-template>
element, wrapped around the host element, like this.
<ng-template [ngIf]="hero">
<div class="name">{{hero.name}}</div>
</ng-template>
ng-container
Use as a grouping element when there is no suitable host element.
Example:
<div>
Pick your favorite hero
(<label><input type="checkbox" checked (change)="showSad = !showSad">show sad</label>)
</div>
<select [(ngModel)]="hero">
<span *ngFor="let h of heroes">
<span *ngIf="showSad || h.emotion !== 'sad'">
<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>
</span>
</span>
</select>
This will not work. Because some HTML elements require all immediate children to be of a specific type. For example, the <select>
element requires children. You can't wrap the options in a conditional or a <span>
.
Try this :
<div>
Pick your favorite hero
(<label><input type="checkbox" checked (change)="showSad = !showSad">show sad</label>)
</div>
<select [(ngModel)]="hero">
<ng-container *ngFor="let h of heroes">
<ng-container *ngIf="showSad || h.emotion !== 'sad'">
<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>
</ng-container>
</ng-container>
</select>
This will work.
More information: Angular Structural Directive