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.

Applies to: Angular 2 to the latest edition of i.e. Angular 8. Angular 9, Angular 10

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-content, 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.


Best Angular Books
The Top 8 Best Angular Books, which helps you to get started with Angular  

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-content

ngTemplateOutlet

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

References

Leave a Comment

Your email address will not be published.

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

Scroll to Top