-
Notifications
You must be signed in to change notification settings - Fork 3
.Translate
We use @ngx-translate/core to translate the application in NGen Angular version project. The following is a step-by-step guide to translate the application.
If you want to translate text in standalone component or module, you can use the TranslateService
to translate the text. Firstly, you need import the TranslateModule
in the module or component.
import { TranslateModule } from '@ngx-translate/core'
@Component({
selector: 'zng-products',
standalone: true,
imports: [CommonModule, TranslateModule],
templateUrl: './products.component.html',
})
export class ProductsComponent {
}
You can either use the TranslateService
, the TranslatePipe
or the TranslateDirective
to get your translation values.
With the service, it looks like this:
translate.get('HELLO', {value: 'world'}).subscribe((res: string) => {
console.log(res);
//=> 'hello world'
});
This is how you do it with the pipe:
<div>{{ 'HELLO' | translate:param }}</div>
And in your component define param
like this:
param = {value: 'world'};
You can construct the translation keys dynamically by using simple string concatenation inside the template:
<ul *ngFor="let language of languages">
<li>{{ 'LANGUAGES.' + language | translate }}</li>
</ul>
Where languages
is an array member of your component:
languages = ['EN', 'FR', 'BG'];
You can also use the output of the built-in pipes uppercase
and lowercase
in order to guarantee that your dynamically generated translation keys are either all uppercase or all lowercase. For example:
<p>{{ 'ROLES.' + role | uppercase | translate }}</p>
role = 'admin';
will match the following translation:
{
"ROLES": {
"ADMIN": "Administrator"
}
}
This is how you use the directive:
<div [translate]="'HELLO'" [translateParams]="{value: 'world'}"></div>
Or even simpler using the content of your element as a key:
<div translate [translateParams]="{value: 'world'}">HELLO</div>
You can use the parameter Default
to set a default value if the translation key is not found.
<div>{{ 'HELLO' | translate:{Default: 'Hello'} }}</div>
In general, we use the Default
parameter to set text in the english language, and translate to other languages in i18n files.
- The translation key should be in camel case and uppercase first letter.
- Put your translate key in global prefix
ZNG
or not. - The translation files in folder
src/assets/i18n
should be named as<language>.json
.