Tutorial

Angular: The ng-container Element

AngularJS

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

ng-container is an element that’s available in Angular 2+ and that can act as the host to structural directives.

You can’t use more than one template binding on an element. So you can’t combine structural directives like this:

<!-- Can't do this -->
<div *ngIf="todos" *ngFor="let todo of todos">
  {{ todo.content }}
</div>

Instead what we usually do is use a wrapper like this:

<div *ngIf="todos">
  <div *ngFor="let todo of todos">
    {{ todo.content }}
  </div>
</div>

This is all well and good, but it adds a useless div element to the DOM. This is where the ng-container element becomes useful. The following behaves exactly the same, but without adding any extra element to the DOM at runtime:

<ng-container *ngIf="todos">
  <div *ngFor="let todo of todos">
    {{ todo.content }}
  </div>
</ng-container>

And this is also really useful when using ngIf on inline content to avoid the need for a bunch of span elements. This…

<div>
  <span *ngIf="error">Oops:</span> {{ message }}
</div>

…can also be used like this:

<div>
  <ng-container *ngIf="error">Oops:</ng-container> {{ message }}
</div>

Avoiding the use of dumb span elements like that can help prevent having unwanted styles applied if some of your CSS rules would normally target them.


ng-container is not just a nicety, because in some cases your HTML markup wouldn’t be valid without it. This would output invalid HTML because only li elements can be children of the ul element:

<ul>
  <div *ngFor="let todo of todos">
    <li *ngIf="todo.content !== 'Get milk'">
      {{ todo.content }}
    </li>
  </div>
</ul>

ng-container saves the day once again there because the following will produce valid HTML:

<ul>
  <ng-container *ngFor="let todo of todos">
    <li *ngIf="todo.content !== 'Get milk'">
      {{ todo.content }}
    </li>
  </ng-container>
</ul>

0 Comments

Creative Commons License