Explain Codes LogoExplain Codes Logo

Using ngIf without an extra element in Angular 2

javascript
angular
template-engineering
best-practices
Alex KataevbyAlex Kataev·Oct 19, 2024
TLDR

Manage *ngIf conditionally rendering sans extra DOM elements with <ng-container>:

<ng-container *ngIf="isVisible">Show this if 'isVisible' is true</ng-container>

<ng-container> creates no footprint in the final output, acting as an invisible wrapper for *ngIf directives.

Mastering the ng-container

The aspiration of minimal, semantic HTML is central to Angular template creation. The <ng-container> directive is an invisible power tool for structural directives like *ngIf and *ngFor, letting you avoid junky, unnecessary DOM elements.

Building semantic tables

HTML tables with conditional rows can become messy if <tr> tags are directly hooked with *ngIf execution. That's invalid HTML and makes browsers sad 😢. But cheer up, <ng-container> has you covered!

<tbody> <ng-container *ngIf="condition"> <tr><td>Content in case condition is true</td></tr> </ng-container> </tbody>

Maintaining HTML standards while rendering tables was never so easy.

Bidding adieu to old template tags

Before modern Angular walked in fashionably late, <template> tag was the old faithful for conditional rendering. But hey, it's time to let go and embrace the new kid on the block — <ng-container>!

Taming loops and async data

Working with loops? Fret not, just cozy up with *ngFor and <ng-container> to avoid superfluous elements:

<ng-container *ngFor="let item of items"> <custom-element [item]="item"></custom-element> <!-- because who needs an extra 'div' party-crashing your DOM party? 🥳 --> </ng-container>

Handling asynchronous data? Use the async pipe with *ngIf inside an <ng-container> directive for smooth sailing:

<ng-container *ngIf="observableData | async as data"> Showy show {{ data.property }} </ng-container>

Ascending to Angular best practices

Understanding Angular semantics is key to building efficient, elegant apps. <ng-container> aligns your dev practices to Angular's vision.

Wrangling elements with ng-container

Examples of <ng-container> in action:

  • Conditional classes: Apply without an extra element:

    <ng-container *ngIf="shouldHighlight"> <div [class.highlight]="true">Highlight if condition is true. Like a beacon in the dark!</div> </ng-container> <!-- Extra div not included! -->
  • Grouping elements: Treat them as a collective under one condition:

    <ng-container *ngIf="showGroup"> <div>First Element</div> <div>Second Element</div> </ng-container> <!-- It's a group thing. Keep the gate lies on ng-container -->

Street smarts with ng-container

Keep these in mind:

  • Over-nesting <ng-container> can lead to performance issues. It's not Inception!
  • Use it only when it's needed. It's a power tool, not a hammer!