Angular:带ngIf的ng-container直接加i18n是否可行?存在哪些问题?
<ng-container *ngIf>: Does It Work? Great question—let's break this down clearly: The first approach (<ng-container *ngIf="anything" i18n>Something to translate</ng-container>) does NOT work reliably for Angular i18n, and here's why:
1. Angular's i18n Tooling Relies on Concrete Elements
Angular's internationalization tools (like ng extract-i18n) are built to scan for translation targets attached to actual DOM elements or text nodes. <ng-container> is a virtual element—it doesn't render any HTML to the final DOM. Attaching the i18n attribute directly to it confuses the extraction process, which often skips text inside a <ng-container> that’s paired with a structural directive like *ngIf.
2. Structural Directives and i18n Don’t Play Nice on the Same Element
The *ngIf directive manipulates the DOM by adding/removing the content inside the <ng-container>. When you combine i18n with *ngIf on the same <ng-container>, Angular’s i18n compiler can’t properly anchor the translation metadata to the text content. i18n needs a stable, non-structural element to associate with the translation marker—something <ng-container> (as a purely structural wrapper) can’t provide.
3. Why the Second Approach Fixes It
Wrapping the text in a <span i18n> inside the <ng-container> gives the i18n tooling a concrete, non-structural element to attach translation data to. The <span> is a real DOM element (even if it’s stylistically invisible) that the extraction tool recognizes, while *ngIf only controls whether the entire block (including the <span>) is rendered. No conflict, no missed translations.
Quick Test to Confirm
Run the extraction command to see the difference firsthand:
ng extract-i18n
You’ll notice the text from the first approach won’t appear in the generated .xlf file, while the second approach’s text will be included correctly.
内容的提问来源于stack exchange,提问作者Magda

