ng2 - Difference between ng-container and ng-template tags

Solution 1:

Both of them are at the moment (2.x, 4.x) used to group elements together without having to introduce another element which will be rendered on the page (such as div or span).

template, however, requires nasty syntax. For example,

<li *ngFor="let item of items; let i = index; trackBy: trackByFn">...</li>

would become

<template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
  <li>...</li>
</template>

You can use ng-container instead since it follow the nice * syntax which you expect and are probably already familiar with.

<ng-container *ngFor="let item of items; let i = index; trackBy: trackByFn">
  <li>...</li>
</ng-container>

You can find more details by reading this discussion on GitHub.


Note that in 4.x <template> is deprecated and is changed to <ng-template>.


Use

  • <ng-container> if you need a helper element for nested structural directives like *ngIf or *ngFor or if you want to wrap more than one element inside such a structural directive;
  • <ng-template> if you need a view "snippet" that you want to stamp at various places using ngForTemplate, ngTemplateOutlet, or createEmbeddedView().

Solution 2:

ng-template is used for the structural directive like ng-if, ng-for and ng-switch. If you use it without the structural directive, nothing happens and it will render.

ng-container is used when you don't have a suitable wrapper or parent container. In most cases, we are using div or span as a container but in such cases when we want to use multiple structural directives. But we can't use more than one structural directive on an element, in that case, ng-container can be used as a container