In many cases when working on your app, you forced to wrap your content with an additional tag when using structural directives.

Let’s see a few examples.

- Using ngIf to wrap multiple nodes:

In the above example, we are forced to add additional tag because we want to use one ngIf for both divs.

This is not the best solution for two reasons:

We are adding unnecessary DOM node. That’s maybe screwed our styles.

One way to get around this is to use the de-sugared version syntax of structural directives.

That’s fine, but we are not using the asterisk anymore, and this leads to inconsistency in our code.

The second solution is the ng-container directive.

<ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node. <ng-container> is rendered as an HTML comment.

So now we can do this:

Nice!

- Use ngSwitch:

Sometimes we need to display text based on the switch statement. The problem is that this forces us to add an additional tag. For example:

But in many cases, we don’t need the additional tag (in this case the span ). Let’s use ng-container to solve this problem:

Now our template is clean!

🔥 Last but Not Least, Have you Heard of Akita?

Akita is a state management pattern that we’ve developed here in Datorama. It’s been successfully used in a big data production environment, and we’re continually adding features to it.

Akita encourages simplicity. It saves you the hassle of creating boilerplate code and offers powerful tools with a moderate learning curve, suitable for both experienced and inexperienced developers alike.

I highly recommend checking it out.