<ng-container>与<ng-template>的性能差异及选型咨询
<ng-container> vs <ng-template>: Performance & Selection Guide Great questions—let’s unpack this so you can pick the right tool for the job without worrying about unnecessary overhead.
Performance Differences: None at All
First things first: there is no performance gap between <ng-container> and <ng-template>. Here’s why:
<ng-container>is essentially a syntactic sugar wrapper that Angular compiles directly into<ng-template>under the hood when paired with structural directives (like*ngIfor*ngFor). It never gets rendered as a real DOM element, just like<ng-template>.- As you noted, Angular de-sugars syntax like
<div *ngFor="let person of persons"></div>into a<ng-template>structure. If you wrote<ng-container *ngFor="let person of persons"><div></div></ng-container>, the compiler would do almost the exact same work—converting the*ngForinto the underlying<ng-template ngFor>binding, with no extra DOM nodes or runtime cost added.
In short: Both are handled identically by Angular’s compiler and runtime. No performance tradeoffs here.
How to Choose Between Them
The decision comes down to your use case, not performance:
Use <ng-container> when:
- You need a logical grouping for elements without adding extra DOM nodes. For example, if you want to apply a single
*ngIfto multiple elements without wrapping them in a<div>or<span>:<ng-container *ngIf="user.isAuthenticated"> <h2>Welcome back, {{user.name}}!</h2> <nav> <a href="/profile">Profile</a> <a href="/settings">Settings</a> </nav> </ng-container> - You want to use the convenient
*syntax for structural directives (like*ngFor,*ngIf) without tying them to a real DOM element.
Use <ng-template> when:
- You need to define a reusable template fragment that you can render dynamically with
ngTemplateOutlet. For example, creating a loading state that you can reuse across components:<ng-template #loadingState> <div class="spinner">Loading content...</div> </ng-template> <!-- Render the template when data is loading --> <div *ngIf="data; else loadingState"> {{data.content}} </div> - You need to work with the raw, un-sugared structural directive syntax (e.g., building custom directives that interact with templates, or using advanced features like
let-context variables directly). For example:<ng-template ngFor let-person [ngForOf]="users" let-index="index"> <div>{{index + 1}}: {{person.name}}</div> </ng-template> - You want to define a template that won’t render automatically (since
<ng-template>is never rendered by default—you have to explicitly reference it with an outlet or directive).
Quick Recap
- Performance: No difference whatsoever. Both are "invisible" to the final DOM and handled the same by Angular.
<ng-container>: Your go-to for grouping elements with structural directives without extra DOM noise.<ng-template>: Use for reusable, manually-controlled template fragments or advanced directive work.
内容的提问来源于stack exchange,提问作者Yashwardhan Pauranik




