NG Container Hack for Structural Directives

Angular: The Full Gamut Edition

Charlie Greenman
September 06, 2020
2 min read
razroo image

In Angular there are two quirks when it comes to structural directives:

<div *ngIf="someVariable">
  <p>This is text.</p>
  <p>This is more text.</p>
</div>
<ul>
  <li *ngFor="let box of boxes" *ngIf="box.item === 'food'">{{ box.name }}</li>
</ul>

The quirk probably naturally arises because for loops and if statements weren't meant to be used within a template. So if we think about it that way, where we can use some sort of Angular functionality to bring it out of the DOM it brings us to ng-container.

Understanding ng-container

In the Angular documentation, ng ng-container is specified as a way to group elements without introducing a new html element.

Some of the examples mentioned include a <span> element that might introduce some accidental styling, or attempting to put a <span> inside of a select element. ng-container will allow for to side step those issues, by not introducing a new element to the actual DOM. We can use the ng-container to solve the quirks we mentioned earlier:

  to Implement Structural Directive&quot;}
&lt;ng-container *ngIf=&quot;someVariable&quot;&gt;
  &lt;p&gt;The show goes on.&lt;/p&gt;
  &lt;p&gt;and on and on and on.&lt;/p&gt;
&lt;/ng-container&gt;

Here, by introducing an ng-container, we no longer have to introduce a new div, if we want the content to show conditionally. Likewise, to solve the issue we had before of being able to use two structural directives, we can do the following:

&lt;ul&gt;
  &lt;ng-container *ngFor=&quot;let box of boxes&quot;&gt;
    &lt;ng-container *ngIf=&quot;box.item === &#39;food&#39;&quot;&gt;
      &lt;li&gt;{{ box.name }}&lt;/li&gt;
    &lt;/ng-container&gt;
  &lt;/ng-container&gt;
&lt;/ul&gt;  

We could technically apply the *ngIf on the li element itself, for consistency sake. If I had a team member that preferred otherwise, I would be more than happy with that, just my preference.

Thank you to Austin Spivey for being the person where I saw this approach from.

Subscribe to the Razroo Angular Newsletter!

Razroo takes pride in it's Angular newsletter, and we really pour heart and soul into it. Pass along your e-mail to recieve it in the mail. Our commitment, is to keep you up to date with the latest in Angular, so you don't have to.

More articles similar to this

footer

Razroo is committed towards contributing to open source. Take the pledge towards open source by tweeting, #itaketherazroopledge to @_Razroo on twitter. One of our associates will get back to you and set you up with an open source project to work on.