ng-container in Angular

In this guide let us look at ng-container in Angular. We use this to create a dummy section in the template, without rendering it in the HTML. This is a pretty useful feature while we work with the structural directives like ngIf, ngFor & ngSwitch. We also look at some of the use cases of the same.

What is ng-container ?

ng-container allows us to create a division or section in a template without introducing a new HTML element. The ng-container does not render in the DOM, but content inside it is rendered. ng-container is not a directive, component, class, or interface, but just a syntax element.

For Example

The following template

Renders as

You can see that the element is absent in the final HTML

Uses of ng-container

It is a very useful directive. Especially when working with structural directives like ngIf, ngFor, etc.

ng-Container with ngFor

For Example, consider the following items. We want to display the items as a list, but only the active items. This requires two directives ngFor to loop through the items and ngIf to check if the items are active

Without ng-container, the only way to achieve this is by using the span element as shown. This adds the unnecessary DOM element. and it may also cause issues with the CSS.

By Replacing the span with ng-container our HTML renders correctly without those extra span elements

ng-container examples

ng-container with ngIf

The div of the ngIf is not necessary here.

ngSwitch with/without ng-container

ngTemplateOutlet

The container is also used as a placeholder for injecting a dynamic template using the ngTemplateOutlet.

References

5 thoughts on “ng-container in Angular”

  1. Ng-container is a directive or not ?

    These 2 lines are contradictory
    -> ng-container is not a directive, component, class, or interface, but just a syntax element.
    -> It is a very useful directive. Especially when working with structural directives like ngIf, ngFor, etc.

Leave a Comment

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

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

Scroll to Top