0
# Translation Service
1
2
Injectable Angular service that provides synchronous code-based translations using translation files in various formats (XLIFF, XLIFF2, XTB).
3
4
## Capabilities
5
6
### I18n Service
7
8
The main translation service that returns a callable function for performing translations.
9
10
```typescript { .api }
11
/**
12
* Injectable Angular service for i18n code translations
13
* Returns a function that translates strings synchronously
14
*/
15
@Injectable()
16
class I18n {
17
constructor(
18
@Inject(TRANSLATIONS_FORMAT) format: string,
19
@Inject(TRANSLATIONS) translations: string,
20
@Inject(LOCALE_ID) locale: string,
21
@Optional()
22
@Inject(MISSING_TRANSLATION_STRATEGY)
23
missingTranslationStrategy?: MissingTranslationStrategy
24
);
25
}
26
27
interface I18n {
28
(def: string | I18nDef, params?: {[key: string]: any}): string;
29
}
30
```
31
32
**Parameters:**
33
- `format` - Translation file format: "xlf", "xlf2", "xliff", "xliff2", or "xtb"
34
- `translations` - Translation file content as string
35
- `locale` - Target locale string
36
- `missingTranslationStrategy` - Optional strategy for handling missing translations (default: Warning)
37
38
**Usage:**
39
The service constructor returns a function that can be called to translate strings. The function accepts either a simple string or an I18nDef object with metadata, plus optional interpolation parameters.
40
41
### Translation Function
42
43
The function returned by the I18n service constructor.
44
45
```typescript { .api }
46
/**
47
* Translates a string or I18nDef object
48
* @param def - String to translate or I18nDef object with metadata
49
* @param params - Optional interpolation parameters
50
* @returns Translated string with interpolations applied
51
*/
52
(def: string | I18nDef, params?: {[key: string]: any}): string;
53
```
54
55
**Examples:**
56
57
```typescript
58
import { I18n } from "@ngx-translate/i18n-polyfill";
59
60
@Component({...})
61
export class MyComponent {
62
constructor(private i18n: I18n) {}
63
64
translateStrings() {
65
// Simple string translation
66
const hello = this.i18n("Hello world");
67
68
// Translation with interpolation
69
const greeting = this.i18n("Hello {{name}}", { name: "John" });
70
71
// Translation with metadata
72
const message = this.i18n({
73
value: "Hello {{name}}",
74
id: "greeting.hello",
75
meaning: "A friendly greeting",
76
description: "Greeting message shown to users"
77
}, { name: "John" });
78
79
// ICU expressions
80
const pluralMessage = this.i18n(
81
"Updated {count, plural, =0 {no items} =1 {one item} other {{{count}} items}}",
82
{ count: 5 }
83
);
84
}
85
}
86
```
87
88
## Angular Integration
89
90
The I18n service integrates with Angular's dependency injection system and requires several providers:
91
92
```typescript
93
import { NgModule } from "@angular/core";
94
import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID, MissingTranslationStrategy } from "@angular/core";
95
import { I18n, MISSING_TRANSLATION_STRATEGY } from "@ngx-translate/i18n-polyfill";
96
97
// Load translation file content
98
const translationFileContent = require("raw-loader!../locale/messages.fr.xlf");
99
100
@NgModule({
101
providers: [
102
I18n,
103
{ provide: TRANSLATIONS, useValue: translationFileContent },
104
{ provide: TRANSLATIONS_FORMAT, useValue: "xlf" },
105
{ provide: LOCALE_ID, useValue: "fr" },
106
{ provide: MISSING_TRANSLATION_STRATEGY, useValue: MissingTranslationStrategy.Warning }
107
]
108
})
109
export class AppModule {}
110
```
111
112
### Dynamic Translation Loading
113
114
For dynamic locale loading using a factory provider:
115
116
```typescript
117
@NgModule({
118
providers: [
119
I18n,
120
{
121
provide: TRANSLATIONS,
122
useFactory: (locale: string) => {
123
locale = locale || 'en';
124
return require(`raw-loader!../locale/messages.${locale}.xlf`);
125
},
126
deps: [LOCALE_ID]
127
},
128
{ provide: TRANSLATIONS_FORMAT, useValue: "xlf" },
129
{ provide: LOCALE_ID, useValue: "fr" }
130
]
131
})
132
export class AppModule {}
133
```
134
135
## Supported Features
136
137
- **String Interpolation**: Named parameters with `{{paramName}}` syntax
138
- **ICU Expressions**: Pluralization and selection with `{param, plural, ...}` and `{param, select, ...}`
139
- **Multiple Formats**: XLIFF (.xlf), XLIFF2 (.xlf2), and XTB formats
140
- **Missing Translation Handling**: Configurable strategies for missing translations
141
- **Synchronous Operation**: No async/await required - translations are available immediately
142
- **Type Safety**: Full TypeScript support with proper type definitions
143
144
## Error Handling
145
146
The service throws errors for:
147
- Invalid translation file formats
148
- Malformed HTML content in translation strings
149
- Parse errors in ICU expressions
150
151
Missing translations are handled based on the configured `MissingTranslationStrategy`:
152
- `Ignore`: Return the source text without warnings
153
- `Warning`: Log warnings and return source text (default)
154
- `Error`: Throw an error for missing translations