Angular i18n (Internationalization) in Pattern A is an AOT-compiled workflow that manages the site in two languages (IT+EN) through i18n="@@id" markers in templates, source messages.xlf (IT), and target messages.en.xlf (EN). Both XLF files are compiled during build, generating two distinct Angular bundles — one per language — where strings are already translated and hardcoded. No external libraries required, no Transloco/ngx-translate, and zero runtime overhead for optimal performance. The cost is inflexibility: adding a new language requires architectural change, not just an additional XLF file. This choice emerged from consolidating a site that managed 18 languages in runtime through dynamic XLF translation — an unsustainable strategy for translation quality, performance, and maintainability. The lesson: choose between linguistic scalability (18+ languages, runtime translation, overhead) and quality+performance (2-4 compiled-AOT languages, zero overhead).
Introduction: Why Consolidate on Pattern A?
In 2026, Federico Calò's portfolio started with an i18n architecture supporting 18 languages total: 2 compiled in AOT (IT and EN through Angular Localize) and 16 served at runtime via dynamic XLF translation (German, French, Spanish, Portuguese, Polish, Dutch, Swedish, Danish, Norwegian, Finnish, Turkish, Japanese, Chinese, Korean, Russian, Arabic). The result was a slow, fragile, and difficult-to-maintain site.
Problems encountered:
- Degraded performance: Loading dynamic XLF files (16 files, ~50KB total) blocked initial parsing and rendering. TTI (Time to Interactive) was 2.5+ seconds.
- Inconsistent translation quality: Translations via Google Translate API at build time, without human review. Many context errors, plurals, grammatical gender issues.
- Maintenance complexity: Every new article or feature required updating 18 translation files. A change to IT copy meant 16 re-translation triggers and re-testing.
- Contradictory architectural decision: Two AOT-compiled languages (IT+EN with `i18n="@@id"` markers) coexisted with 16 runtime languages (via dynamic XLF loader). This duality created technical debt.
Strategic decision (2026-05-31): consolidate to Pattern A — a single i18n architecture, IT+EN compiled AOT with `i18n="@@id"` markers. The 16 runtime languages were de-indexed and served as 410 Gone with geo-redirect to IT or EN. Result: fast site (LCP < 2.5s), maintainable (1 i18n workflow, no translation API), and focused on primary IT/EN quality.
What is Angular i18n Pattern A?
Pattern A is the official workflow of Angular Localize, the built-in library for internationalization. It consists of 4 artifacts:
1. Markers in HTML Templates
Every string to translate is marked with i18n="@@id" in the template:
<h1 i18n="@@article.title">{{ title }}</h1>
<p i18n="@@article.excerpt">{{ excerpt }}</p>
<button i18n="@@action.readMore">Read more</button>
2. Source XLF (IT)
The messages.xlf file contains all strings to translate, automatically extracted by Angular CLI:
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="it" datatype="plaintext" original="ng2">
<body>
<trans-unit id="article.title">
<source>Angular i18n a scala: da 18 lingue a un workflow IT+EN sostenibile</source>
</trans-unit>
<trans-unit id="article.excerpt">
<source>Consolidamento i18n in Angular 21 SSR...</source>
</trans-unit>
<trans-unit id="action.readMore">
<source>Leggi di più</source>
</trans-unit>
</body>
</file>
</xliff>
3. Target XLF (EN)
The messages.en.xlf file is a copy of messages.xlf with translations in <target> tags:
<?xml version="1.0" encoding="UTF-8" ?>
<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2">
<file source-language="it" target-language="en" datatype="plaintext" original="ng2">
<body>
<trans-unit id="article.title">
<source>Angular i18n a scala: da 18 lingue a un workflow IT+EN sostenibile</source>
<target>Angular i18n at Scale: From 18 Languages to a Sustainable IT+EN Workflow</target>
</trans-unit>
<trans-unit id="article.excerpt">
<source>Consolidamento i18n in Angular 21 SSR...</source>
<target>i18n consolidation in Angular 21 SSR...</target>
</trans-unit>
<trans-unit id="action.readMore">
<source>Leggi di più</source>
<target>Read more</target>
</trans-unit>
</body>
</file>
</xliff>
4. $localize Template Literal in TypeScript
In TypeScript code, use the $localize template literal for dynamic strings (not in HTML template):
// src/app/services/blog.service.ts
export class BlogService {
getArticleLabel(count: number): string {
return $localize`:@@article.count:You have ${count} articles available`;
}
getWelcomeMessage(name: string): string {
return $localize`:@@welcome.user:Welcome, ${name}!`;
}
}
During build, Angular Localize extracts all strings marked with `i18n` and `$localize`, compiles them into two distinct bundles (one for IT, one for EN), and that's it.
Angular Configuration: Step-by-Step Setup
Configuration requires three files:
Step 1: Install @angular/localize
npm install @angular/localize
# Add the polyfill in src/main.ts
Step 2: Enable i18n in angular.json
{
"projects": {
"portfolio": {
"i18n": {
"sourceLocale": "it",
"locales": {
"en": {
"translation": "src/locale/messages.en.xlf",
"baseUrl": "/en/"
}
}
},
"architect": {
"build": {
"options": {
"localize": true
}
}
}
}
}
}
Step 3: Build Automation in package.json
{
"scripts": {
"extract-i18n": "ng extract-i18n --output-path src/locale",
"i18n:validate": "node scripts/validate-i18n.mjs",
"i18n:xlf": "npm run extract-i18n && npm run i18n:validate",
"build": "npm run i18n:xlf && ng build --configuration production",
"build:ssr": "npm run build && npm run build:server"
}
}
Build Gate: Trans-unit Parity IT+EN
A frequent problem: adding i18n keys in IT without syncing EN. The build gate verifies that messages.xlf and messages.en.xlf have the same number of trans-unit (strings):
// scripts/validate-i18n.mjs
import fs from 'fs';
import { parseStringPromise } from 'xml2js';
async function validateI18n() {
const itXlf = fs.readFileSync('src/locale/messages.xlf', 'utf8');
const enXlf = fs.readFileSync('src/locale/messages.en.xlf', 'utf8');
const itData = await parseStringPromise(itXlf);
const enData = await parseStringPromise(enXlf);
const itCount = itData.xliff.file[0].body[0]['trans-unit'].length;
const enCount = enData.xliff.file[0].body[0]['trans-unit'].length;
if (itCount !== enCount) {
console.error(`❌ i18n Mismatch: IT=${itCount} trans-unit, EN=${enCount}`);
console.error(' Run: npm run i18n:xlf');
process.exit(1);
}
console.log(`✓ i18n Valid: IT=${itCount} trans-unit, EN=${enCount}`);
}
validateI18n().catch(console.error);
This gate is executed before each build and blocks the process if languages don't match.
Automatic i18n Key Extraction
Angular CLI automatically extracts all strings marked with i18n="@@id":
npm run extract-i18n
# Generated src/locale/messages.xlf with all keys
Operational workflow:
- Add new strings to template with
i18n="@@new.key" - Run
npm run extract-i18nto updatemessages.xlf - Translate new trans-unit in
messages.en.xlf - Run
npm run i18n:validateto verify parity - Commit and build
Prerender per Language
In SSR, the build generates two complete bundles (IT and EN). During prerender, each page is generated in both languages:
ng build --configuration production --localize
# Generates:
# - dist/portfolio/it/ [IT pages]
# - dist/portfolio/en/ [EN pages]
# - dist/portfolio/server/ [SSR server]
The Express server serves pages from the correct directory based on language:
// src/server.ts
import express from 'express';
import { ngExpressEngine } from '@nguniversal/express-engine';
const server = express();
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('views', 'dist/portfolio');
server.get('/:lang/*', (req, res) => {
const { lang } = req.params;
const validLangs = ['it', 'en'];
if (!validLangs.includes(lang)) {
return res.redirect('/it');
}
res.render(`${lang}/index`, { req });
});
server.listen(4000, () => {
console.log('SSR Server listening on port 4000');
});
The Strategic Decision: From 18 Languages to Pattern A
In May 2026, the portfolio managed 18 languages with two parallel approaches:
- 2 AOT languages: IT and EN compiled in bundle with `i18n="@@id"` markers
- 16 runtime languages: German, French, Spanish and others, loaded dynamically from XLF files at runtime via
registerLocaleDataand served throughActivatedRoute.data['locale']
In parallel, the site also supported Transloco as fallback for new development. The result was a complex, fragmented hybrid architecture, difficult to maintain.
Critical Problems with the Previous Architecture
- Performance: Loading 16 additional XLF files (50KB total) blocked rendering. TTI was 2.5-3 seconds.
- Technical debt: Every feature required synchronization across 3 different i18n architectures (Angular Localize AOT, XLF runtime, Transloco).
- Low-quality translation: 16 languages automatically translated via Google Translate API without human review. Systematic errors in plurals, context, formality.
- Maintainability: Adding a new article meant translating it to 18 languages. Modifying IT copy triggered 16 automatic re-translations and 16 tests.
Trade-off Reasoning
The decision was:
Choose between two mutually exclusive architectural strategies: (A) unlimited linguistic scalability at cost of degraded performance and low-quality translation, or (B) focus on 2 high-quality languages (IT primary, EN secondary) with optimal performance, simple maintainability, and zero cost. Decision: (B) Pattern A.
Implementation of the decision (2026-05-31):
- Removed Transloco completely from codebase
- Removed runtime loading of 16 languages XLF (cost 50KB gzip + TTI +500ms)
- Migrated all pages to `i18n="@@id"` markers with source IT + target EN
- Generated 410 Gone de-indexing for 16 dismantled languages, with geo-redirect to IT or EN
- Implemented trans-unit parity build gate to prevent IT/EN desynchronization
- Updated deployment and maintenance runbook
Measured impact (post-consolidation):
- LCP: 3.2s → 2.1s (35% improvement)
- TTI: 2.8s → 1.8s (36% improvement)
- Bundle size: 1.2MB → 820KB (31% reduction)
- Build time: 340s → 155s (54% reduction)
- Days to add article: 2 (IT+EN) vs 4 (18 languages)
Use Case: Adding a New Article
Operational workflow post-consolidation:
Step 1: Write IT Content
<!-- src/app/pages/blog/article.component.html -->
<article>
<h1 i18n="@@blog.9232.title">{{ article.title }}</h1>
<p i18n="@@blog.9232.excerpt">{{ article.excerpt }}</p>
<div>{{ article.content }}</div>
</article>
Step 2: Extract Keys
npm run extract-i18n
# Generates/updates src/locale/messages.xlf
Step 3: Add EN Translations
Manually in src/locale/messages.en.xlf, or via Ollama (see next):
<trans-unit id="blog.9232.title">
<source>Angular i18n a scala: da 18 lingue a un workflow IT+EN sostenibile</source>
<target>Angular i18n at Scale: From 18 Languages to a Sustainable IT+EN Workflow</target>
</trans-unit>
Step 4: Validate Parity
npm run i18n:validate
# ✓ i18n Valid: IT=2847 trans-unit, EN=2847
Step 5: Build and Deploy
npm run build
# Generates dist/portfolio/{it,en}/ with site compiled in both languages
git add .
git commit -m "feat(blog): new article 9232 IT+EN"
ssh portfolio@vps && git pull && systemctl restart portfolio-frontend
Total time: ~30 minutes (write IT, extract keys, translate EN, validate, build).
FAQ: Frequently Asked Questions on Pattern A
Q: How to translate to English automatically with i18n validate?
Pattern A doesn't support built-in automatic translation. In the portfolio, EN translation happens manually or via Ollama on-prem (llama3.1:8b) through a prebuild script. See npm run i18n:translate in the i18n runbook.
Q: What if I forget to add a string in messages.en.xlf?
The build gate detects it and blocks the build. During prerender, Angular compiles each language independently; if a string is missing in EN, the IT version will be used (fallback). But the build gate forces you to sync before producing artifacts.
Q: Can I add a third language (e.g., French) with Pattern A?
Yes, but it requires architectural change: add messages.fr.xlf to angular.json, translate all strings, regenerate build with --localize. Effort: ~200 hours for a 1000+ page site. This is why the trade-off of Pattern A focuses on 2 maximum languages.
Q: What happens to hreflang links if I use Pattern A?
hreflang must be configured at router and sitemap level. Each IT URL has a hreflang link to corresponding EN and vice versa. Example:
// IT page
<link rel="alternate" hreflang="en" href="https://federicocalo.dev/en/blog/angular-i18n-18-lingue" />
<link rel="alternate" hreflang="it-IT" href="https://federicocalo.dev/it/blog/angular-i18n-18-lingue" />
// EN page
<link rel="alternate" hreflang="it" href="https://federicocalo.dev/it/blog/angular-i18n-18-lingue" />
<link rel="alternate" hreflang="en-US" href="https://federicocalo.dev/en/blog/angular-i18n-18-lingue" />
Q: How to handle plurals and grammatical gender with i18n marker?
Angular Localize supports ICU Message Format (MessageFormat) for plurals and conditions. Example:
<p i18n="@@articles.count">
{ count, plural,
=0 {No articles}
=1 {One article}
other {{{ count }} articles}
}
</p>
In the template TypeScript, pass the count variable and Angular automatically interpolates the correct form in IT and EN.
Conclusion and Lessons Learned
Pattern A (Angular Localize with `i18n="@@id"` markers and AOT compilation) is the right choice when:
- Target is 1-2 primary languages (in portfolio case: IT and EN)
- Translation quality is critical (human review, terminology consistency)
- Performance is a priority (zero runtime overhead)
- Long-term maintainability is important (single i18n architecture)
It's not the right choice for:
- Sites with 10+ languages (use Transloco, ngx-translate, or similar)
- Real-time geo-dynamic localization (requires different architecture)
- CMS with translations managed by admin (headless CMS)
The strategic lesson from i18n consolidation in portfolio (2026-05-31):
Scalability and quality are trade-offs. In 2026, it's more strategic to offer excellent experience in 2 languages (IT+EN with 2.1s LCP performance) rather than mediocre experience in 18 (with 3.2s LCP performance and incomplete translations). Focus beats diffusion.
For questions on Pattern A implementation, see docs/13_i18n/01_piano_riduzione_2_lingue_it_en.md in the portfolio repository.

Commenti
Caricamento commenti...
Sign in to comment