DEV Community

Austin Spivey for Wia

Posted on

Angular: Structural directives like *ngIf and *ngFor without the extra elements

One drawback I've found with Angular is that you often found yourself adding unnecessary DOM elements to your templates, just so you can wrap a block of elements in an *ngIf statement. See the below example:

<div *ngIf="someVariable">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
  <p>Lorem ipsum dolor sit amet.</p>
</div>
Enter fullscreen mode Exit fullscreen mode

The wrapping div isn't necessarily needed here, and these unneeded elements can result in messy markup, and sometimes make writing CSS rules more difficult.

The solution is the ng-container directive, a grouping element that doesn't get added to the DOM at all, and thus won't affect your layout. Here's the above example again, this time using ng-container.

<ng-container *ngIf="someVariable">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
  <p>Lorem ipsum dolor sit amet.</p>
</ng-container>
Enter fullscreen mode Exit fullscreen mode

Another issue I've come across is that you can't have more than one structural directive on the same element, e.g. you can't apply both *ngIf and *ngFor to the same element. The below code will result in an error:

<ul>
  <li *ngFor="let item of items" *ngIf="item.foo === 'bar'">{{ item.text }}</li>
</ul>
Enter fullscreen mode Exit fullscreen mode

Rather than adding the extra wrapping DOM element, we'll use the ng-container directive again:

<ul>
  <ng-container *ngFor="let item of items">
    <ng-container *ngIf="item.foo === 'bar'">
      <li>{{ item.text }}</li>
    </ng-container>
  </ng-container>
</ul>
Enter fullscreen mode Exit fullscreen mode

With this technique, you can ensure that there are no unnecessary elements in your DOM.

Discussion (2)

Collapse
tonejac profile image
Tony Jacobson • Edited on

OMG!! <ng-container> That is a game-changer for me! Thank you for sharing it. For whatever reason I had no idea it existed!!

Thanks for this article!

Collapse
koczkadavid profile image
David Koczka

This is a pretty neat way, to keep the DOM clean. Thank you!