Can be used when we required Multiple Structural directives

TechnoFunnel presents another article to learn and understand use cases for “ng-container”. “ng-container” can be used at multiple places and can resolve multiple issues. Lets look for the use case scenarios when “ng-container” would be very useful while development.

Angular ng-container, Techno Funnel, Angular Interview, Angular ng-template

What is Ng-container in Angular?

“ng-container” is a logical container which can contain multiple elements within it. ng-container is not rendered on the screen as an element, instead it is displaced as a comment in HTML. We can group components within ng-container, since it is not rendered as a HTML tag, it do not interface with styles and layout of the component. It acts as a dummy component acting as a parent for other components.


In the output above, we can see that there is no container that is rendered for H1 and H2 Tag. Instead we can see a comment “ng-container”.
What is the purpose of Ng-container in angular?
“ng-container” can be used for the following scenario:
It can act as a container for other elements which is not actually rendered on the screen. So it can be rendered as parent element for other others
We can use “ng-container”, where multiple Structural Directives are required. By design, Angular cannot have multiple structural directive on the same components. We can do the same with “ng-container”
“ng-container” can be used to display conditional templates. We can select template to be displayed on the basis of certain conditions.
Using “ng-container” as a Parent Element
As the name suggest, “ng-container” can be used as a container element to enclose other elements. It acts as the parent which is itself not displayed on the screen then the application is rendered.

The example given above shows that the “ng-container” can be used as a parent element for other element without being rendered.
Can be used when we required Multiple Structural directives
We can use “ng-container” to cater scenario where we require multiple structural directives. In the code below, we have “*ngIf” and “*ngFor” in the same element. The scenario, will throw error since we cannot have multiple structural directive in same element.

The error for the following is specified below:

In order to resolve the same, we can have “ng-container”, where we can put down one of the structural directive and the other structural directive can be placed on the element itself. This way we don’t have 2 structural directive on the same element.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.