BP165: Use ng-container to reduce the number of DOM elements

The ng-container is a structural directive that does not create any DOM element. It is used to group elements together and apply structural directives like ngIf and ngFor to them without creating an extra DOM element. This can improve performance by reducing the number of DOM elements and making the code more readable.

For example, consider the following code:

<div *ngIf="condition">
  <h1>Title</h1>
  <p>Paragraph</p>
</div>

This code creates an extra div element even when the condition is false. To avoid this, we can use ng-container as follows:

<ng-container *ngIf="condition">
  <h1>Title</h1>
  <p>Paragraph</p>
</ng-container>

This code does not create an extra div element and improves the performance of the application.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play