Angular i18n với Transloco: Hướng dẫn thiết lập và dịch thuật
Từ cài đặt đến môi trường thực tế: cấu hình Transloco, xử lý số nhiều bằng cú pháp ICU, thêm chuỗi dự phòng ngôn ngữ thông minh và tự động hóa dịch thuật bằng AI.
Cài đặt Transloco
Transloco là thư viện i18n bên thứ ba phổ biến nhất cho Angular. Thư viện hỗ trợ tải bản dịch khi chạy, định dạng thông điệp ICU, phạm vi tải lười và API template gọn gàng với cả directive cấu trúc lẫn pipe.
npm install @jsverse/translocoCấu hình Transloco
Đăng ký Transloco trong cấu hình ứng dụng. Bạn cần khai báo các ngôn ngữ có sẵn, đặt ngôn ngữ mặc định và cấu hình bộ tải bản dịch. Transloco hỗ trợ cả component độc lập (Angular 14 trở lên) và mẫu NgModule.
Component độc lập (Khuyên dùng)
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import {
provideTransloco,
TranslocoHttpLoader,
} from '@jsverse/transloco';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTransloco({
config: {
availableLangs: ['en', 'de', 'ja', 'es', 'fr'],
defaultLang: 'en',
fallbackLang: 'en',
reRenderOnLangChange: true,
prodMode: true,
},
loader: TranslocoHttpLoader,
}),
],
};Mẫu NgModule
// app.module.ts
import { NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
TranslocoModule,
TRANSLOCO_LOADER,
TranslocoHttpLoader,
provideTransloco,
} from '@jsverse/transloco';
@NgModule({
imports: [TranslocoModule],
providers: [
provideTransloco({
config: {
availableLangs: ['en', 'de', 'ja', 'es', 'fr'],
defaultLang: 'en',
fallbackLang: 'en',
reRenderOnLangChange: true,
prodMode: true,
},
loader: TranslocoHttpLoader,
}),
],
})
export class AppModule {}Tạo tệp bản dịch
Tạo một tệp JSON cho mỗi ngôn ngữ trong src/assets/i18n/. Dùng khóa lồng nhau để sắp xếp chuỗi theo tính năng. Transloco dùng định dạng thông điệp ICU cho số nhiều và biến.
// assets/i18n/en.json
{
"nav": {
"home": "Home",
"about": "About",
"settings": "Settings"
},
"greeting": "Hello, {{ name }}!",
"cart": {
"itemCount": "{count, plural, one {# item} other {# items}}"
}
}
// assets/i18n/de.json
{
"nav": {
"home": "Startseite",
"about": "Uber uns",
"settings": "Einstellungen"
},
"greeting": "Hallo, {{ name }}!",
"cart": {
"itemCount": "{count, plural, one {# Artikel} other {# Artikel}}"
}
}Dùng bản dịch trong template và service
Transloco cung cấp ba cách dịch trong template: directive cấu trúc (*transloco), pipe (| transloco) và service (TranslocoService) cho mã TypeScript. Directive cấu trúc phù hợp nhất với đa số trường hợp vì chỉ tạo một subscription và cung cấp hàm dịch cho toàn bộ khối template.
Dịch trong template
<!-- Using the transloco directive (recommended) -->
<ng-container *transloco="let t">
<h1>{{ t('greeting', { name: userName }) }}</h1>
<nav>
<a routerLink="/">{{ t('nav.home') }}</a>
<a routerLink="/about">{{ t('nav.about') }}</a>
</nav>
</ng-container>
<!-- Using the transloco pipe -->
<h1>{{ 'greeting' | transloco:{ name: userName } }}</h1>
<!-- Using the structural directive with read -->
<ng-container *transloco="let t; read: 'nav'">
<a routerLink="/">{{ t('home') }}</a>
<a routerLink="/about">{{ t('about') }}</a>
</ng-container>Dịch trong service (TypeScript)
import { Component, inject } from '@angular/core';
import { TranslocoService } from '@jsverse/transloco';
@Component({
selector: 'app-notification',
template: '<span>{{ message }}</span>',
})
export class NotificationComponent {
private translocoService = inject(TranslocoService);
message = '';
showSuccess() {
// Translate in TypeScript
this.message = this.translocoService.translate('notifications.saved');
}
switchLanguage(lang: string) {
this.translocoService.setActiveLang(lang);
}
}Xử lý số nhiều bằng định dạng thông điệp ICU
Transloco dùng định dạng thông điệp ICU cho số nhiều và biểu thức select. ICU tự động xử lý quy tắc số nhiều phức tạp — tiếng Ả Rập (6 dạng), tiếng Nga (3 dạng), tiếng Nhật (1 dạng) — chỉ từ một chuỗi thông điệp. Hãy khai báo quy tắc số nhiều trong tệp bản dịch, Transloco sẽ chọn đúng dạng khi chạy.
// assets/i18n/en.json
{
"cart": {
"itemCount": "{count, plural, one {# item} other {# items}}",
"emptyMessage": "Your cart is empty"
},
"notifications": {
"unread": "{count, plural, =0 {No new notifications} one {# new notification} other {# new notifications}}"
}
}
// assets/i18n/ar.json — Arabic has 6 plural forms
{
"cart": {
"itemCount": "{count, plural, zero {لا عناصر} one {عنصر واحد} two {عنصران} few {# عناصر} many {# عنصرًا} other {# عنصر}}"
}
}
// Template usage:
// <span>{{ t('cart.itemCount', { count: cartItems.length }) }}</span>Chuỗi dự phòng ngôn ngữ thông minh với angular-locale-chain
Theo mặc định, Transloco dùng ngôn ngữ mặc định khi thiếu khóa bản dịch. Người dùng pt-BR sẽ thấy tiếng Anh thay vì bản dịch pt-PT hoàn toàn phù hợp. angular-locale-chain khắc phục bằng cách hợp nhất sâu bản dịch từ một chuỗi dự phòng có thể cấu hình trước khi chuyển cho Transloco. Mọi khóa đều có giá trị, không còn khoảng trống hay bản dịch bị thiếu.
npm install angular-locale-chain// app.config.ts — with angular-locale-chain
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import {
provideTransloco,
TranslocoHttpLoader,
TRANSLOCO_LOADER,
TRANSLOCO_FALLBACK_STRATEGY,
} from '@jsverse/transloco';
import {
LocaleChainLoader,
LocaleChainFallbackStrategy,
} from 'angular-locale-chain';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTransloco({
config: {
availableLangs: ['en', 'fr', 'fr-CA', 'pt', 'pt-BR', 'de', 'de-AT'],
defaultLang: 'en',
fallbackLang: 'en',
reRenderOnLangChange: true,
prodMode: true,
},
}),
{
provide: TRANSLOCO_LOADER,
useFactory: () => {
const inner = new TranslocoHttpLoader();
return new LocaleChainLoader(inner, {
defaultLocale: 'en',
});
},
},
{
provide: TRANSLOCO_FALLBACK_STRATEGY,
useFactory: () => new LocaleChainFallbackStrategy(),
},
],
};Cấu trúc tệp khuyên dùng
my-angular-app/
├── src/
│ ├── assets/
│ │ └── i18n/
│ │ ├── en.json # Source language
│ │ ├── de.json # German
│ │ ├── ja.json # Japanese
│ │ ├── es.json # Spanish
│ │ └── fr.json # French
│ ├── app/
│ │ ├── app.config.ts # Transloco provider config
│ │ ├── app.component.ts
│ │ └── components/
│ │ └── lang-switcher/
│ │ └── lang-switcher.component.ts
│ └── main.ts
├── angular.json
└── package.jsonTự động hóa dịch thuật
Sau khi thiết lập xong Transloco, hãy dùng AI để dịch các tệp ngôn ngữ. Trong IDE, bạn có thể yêu cầu trợ lý AI dịch tệp JSON nguồn hoặc dùng i18n Agent CLI trong quy trình CI/CD để tự động hóa hoàn toàn việc bản địa hóa.
# In your IDE, ask your AI assistant:
> Translate src/assets/i18n/en.json to German, Japanese, and Spanish
✓ de.json created (1.2s)
✓ ja.json created (1.5s)
✓ es.json created (1.1s)
# Or use the CLI in CI/CD:
npx i18n-agent translate src/assets/i18n/en.json --lang de,ja,esTự động kiểm soát chất lượng bản dịch
Lỗi thường gặp
Bản dịch hiện khóa thô
Không phân giải được khóa theo phạm vi
Cảnh báo console trong môi trường thực tế
Bản dịch nhấp nháy khi chuyển route
Người dùng theo vùng thấy tiếng Anh thay vì ngôn ngữ cha
Dùng thử i18n Agent ngay
Thả tệp bản dịch của bạn vào đây
JSON, YAML, PO, XML, CSV, Markdown, Properties
hoặc nhấp để duyệt
Ngôn ngữ đích
Dự phòng ngôn ngữ với angular-locale-chain
Khi thiếu khóa bản dịch trong một ngôn ngữ vùng như pt-BR, TranslocoLoader của Angular chuyển thẳng sang ngôn ngữ mặc định thay vì kiểm tra ngôn ngữ cha pt trước.
npm install angular-locale-chainimport { LocaleChainLoader } from 'angular-locale-chain';
new LocaleChainLoader(innerLoader, {
fallbacks: {
'pt-BR': ['pt', 'en'],
'zh-Hant-HK': ['zh-Hant', 'zh', 'en'],
},
defaultLocale: 'en',
});Xem Hướng dẫn dự phòng ngôn ngữ để biết danh sách đầy đủ các framework được hỗ trợ và 75 chuỗi tích hợp sẵn. Learn more →