Search⌘ K

A Useful Trick with `ng-container`

Explore how to use the ng-container directive in Angular to apply structural directives without adding unnecessary DOM elements. This lesson helps you write cleaner templates by guarding content against null values and maintaining optimal DOM structure for better performance.

The <ng-container> directive is very powerful, and we should definitely learn to use it. In this lesson, we’ll learn a useful trick that will be quite handy when we work with structural directives.

The ng-container

This directive is especially useful for us because it adds an element to the HTML template that we can use, but Angular removes it during the render time. In other words, we can use as many ng-container elements as we want, and it does not influence the number of DOM nodes at all.

Why is this so useful?

The following few examples demonstrate the usefulness of this directive.

<img [src]="user.avatar"">

<article>
	<p> {{ user.name }} </p>
	<p> {{ user.mailAddress }} </p>
</article>

We’ll start with a simple template for displaying the user’s ...