tezvyn:

<ng-container>: Group Elements Without a DOM Footprint

AI-drafted, machine-checkedSource: angular.devintermediate
<ng-container>: Group Elements Without a DOM Footprint

<ng-container> is an Angular grouping element that doesn't render to the DOM. Use it to apply a structural directive like *ngIf to multiple elements without adding an extra <div> that could break your layout.

WHY IT EXISTS Structural directives like *ngIf or *ngFor apply to a single host element. To apply one to a group of sibling elements, you'd need a wrapper. But adding a or just for logic adds an unnecessary element to the DOM, which can break layouts or create invalid HTML.

THE MENTAL MODEL <ng-container> is like scaffolding for Angular's template logic. You use it to hold a structural directive that affects a group of elements, but once Angular processes the template, the scaffolding itself is removed, leaving only the resulting elements in the DOM. It's a marker for the compiler, not an element for the browser.

HOW IT WORKS Angular's compiler recognizes <ng-container> as a special instruction. When it sees one with a structural directive, it evaluates the directive's expression. If the condition passes (for *ngIf) or for each item in a collection (for *ngFor), it stamps out the content inside the <ng-container> in its place. The <ng-container> tag itself is never added to the final DOM tree, resolving to a harmless comment node.

WHEN TO USE IT Use it whenever you need to conditionally render or repeat a block of sibling elements without a common parent. This is critical in situations with strict parent-child HTML rules, like rendering multiple <td> elements within a <tr>, multiple <option> elements in a <select>, or multiple <li> elements in a <ul>. It's also perfect for avoiding extra wrappers that would interfere with direct-child CSS selectors like flex > *.

WHEN NOT TO USE IT Don't use <ng-container> if you actually need a wrapper element for styling, accessibility (e.g., a role attribute), or to attach event listeners to the group as a whole. In those cases, a or other semantic element is the correct choice. Applying styles, IDs, or attributes to an <ng-container> is pointless as it won't exist in the DOM to receive them.

ONE CANONICAL EXAMPLE Imagine you need to display two table cells only if a condition is met. Wrapping two <td>s in a inside a <tr> is invalid HTML. The correct solution is: <ng-container *ngIf="isEditable"><td><button>Edit</button></td><td><button>Delete</button></td></ng-container>. If isEditable is true, the two <td>s are rendered directly inside their parent <tr>, maintaining a valid table structure.

Read the original → angular.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.