BP168: Use ngIf instead of ngShow/ngHide to reduce the number of DOM elements

The ngIf directive removes or recreates a portion of the DOM tree based on a condition. This is different from ngShow/ngHide, which simply hides or shows an element by adding or removing the 'display: none' CSS property. Using ngIf can improve performance by reducing the number of DOM elements that need to be rendered and updated.

For example, consider a scenario where you have a list of items and you want to show a message if the list is empty. Using ngShow/ngHide, you would need to add an extra element to the DOM to display the message, even if the list is not empty. With ngIf, you can conditionally render the message only when the list is empty, reducing the number of elements in the DOM.

<div *ngIf="list.length === 0">
  <p>The list is empty.</p>
</div>

<div *ngIf="list.length">
  <ul>
    <li *ngFor="let item of list">{{ item }}</li>
  </ul>
</div>

In the above example, the first div element is only rendered when the list is empty, thanks to the ngIf directive. This reduces the number of elements in the DOM and can improve performance.

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

Get it on Google Play