
In Angular, directives fall under 3 major categories:
- Built-in directives
- Attribute directives
- Structural directives
ng-template falls under the category of structural directives, which help us define a template that doesn’t render anything by itself, but conditionally renders them to the DOM. It helps us create dynamic templates that can be customized and configured
ng-container:
In some cases when you do not want to add an extra HTML element to the DOM , for example like div or span , but we need a wrapper around children components, in that case we can use ng-container. It will accept Angular directives like ngIf, ngFor etc. ng-container will serve as wrappers but do not add any extra element to the DOM.
<ng-container *ngIf="list.length else empty">
<ng-container *ngTemplateOutlet="itemList; context:tag"> </ng-container>
</ng-container>
<ng-template #itemList let-myCategory="category" let-myFramework="framework">
<h1>{{ myFramework }} / {{myCategory }}</h1>
<ul>
<ng-template ngFor let-item [ngForOf]="list">
<li>{{item.name}}</li>
</ng-template>
</ul>
</ng-template>
<ng-template #empty>
<div>Sorry, The list is empty</div>
</ng-template>
ng-template:
ng-template is a template that defines composition of elements(template content) . But Angular does not render it by default until we specifically render it.
<div class="list" *ngIf="list.length else products">
<ul>
<li *ngFor="let item of list">{{item.name}}</li>
</ul>
</div>
<ng-template #products>
<div>Sorry, The list is empty</div>
</ng-template>
<!-- OR Another more elaborate syntax-->
<ng-template [ngIf]="list.length" [ngIfElse]="products">
<ul>
<ng-template ngFor let-item [ngForOf]="list">
<li>{{item.name}}</li>
</ng-template>
</ul>
</ng-template>
<ng-template #products>
<div>Sorry, The list is empty</div>
</ng-template>