Angular – Difference between ng-container and ng-template


Overview: 

ng-container and ng-template, both are angular elements which will work like containers with HTML elements, but with different purpose/use cases.

Lets see what is the use of ng-container and ng-template below:

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.

Example: 

In Angular you cannot apply two or more structural directives( such as ngIf, ngFor, ngSwitch etc) on an element. So the next solution may be: 

This will work, but now we are introducing a div element, which we don’t need.

In such cases, We can solve this using ng-container like below:

With this, the DOM won’t include ng-container, so we are not adding any extra element that we do not need. Angular renders the ng-container element as a comment in the DOM. Like this we can use another structural directive before the ul element. We can use more ng-containers

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.

Example: 

When we check the above example in browser, in HTML source code , we will find ng-template block will be commented like below: 

From this we can understand that it’s only defined in the source code but it is not rendered.

So the use case will be like:

So we have to render it to the DOM when there are no apps like below:

The template will never be rendered until we render it.

So ng-template is, We can store a piece of UI code using template element and apply it to the DOM conditionally. 

Conclusion: Difference between ng-container and ng-template:

ng-container will serve as a container for elements, It will accept structural directives like ngFor, ngIf etc. But it will never get rendered to the DOM. Meanwhile ng-template allows us to create template content, this also will not render to the DOM until we specifically/conditionally add it to the DOM.

Leave A Comment

Your email address will not be published. Required fields are marked *