Originally published at shahar.kazaz
In this article, I will show you how easily we can add internalization (i18n) support to Angular SSR using the next generation Angular internalization library Transloco. Let's get started.
First, let's create a brand new Angular CLI project:
npx @angular/cli new transloco-ssr
Now, add SSR support by using @nguniversal/express-engine
schematics:
ng add @nguniversal/express-engine --clientProject <PROJECT-NAME>
Add Transloco to your project by using schematics:
ng add @ngneat/transloco
Choose your supported languages, and answer Yes
for the SSR question. Now you can see that it created the translation files, the loader, and added everyhing it needs to the AppModule
.
When using Angular SSR, we need to change our loader base path to be absolute instead of relative, for it to work. This is already done for you.
The only thing you need to do is modify the new baseUrl
property in each one of the environment
files based on your application:
export const environment = {
production: false,
baseUrl: 'http://localhost:4200' <====
};
// environment.prod.ts
export const environment = {
production: true,
baseUrl: 'http://localhost:4000' <====
};
Now let's add a new key to our translation files:
{
"title": "Angular SSR with Transloco english"
}
And let's use it in our template:
<ng-template transloco let-t>
{{ t.title }}
</ng-template>
Let's build our application for production using the following commands:
npm run build:ssr
npm run serve:ssr
Open your browser and navigate to http://localhost:4000
and Viola! We did it!
Let's see the source HTML file:
image
We have got a working application with SSR and internalization (i18n) support in 5 minutes.
Bonus
We can use the accept-language
header to set the preferred user language automatically. The Accept-Language request HTTP header advertises which languages the client can understand, and which locale variant is preferred.
import { Component, Inject, Optional } from '@angular/core';
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';
import { TranslocoService } from '@ngneat/transloco';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(@Optional() @Inject(REQUEST) private request: Request, private translocoService: TranslocoService) {
if (request.headers) {
translocoService.setActiveLang(normalize(request.headers['accept-language']));
}
}
}
The accept-language
headers return the following string:
'accept-language': 'en-US,en;q=0.9,he;q=0.8,ru;q=0.7,fr;q=0.6,pt;q=0.5',
You need to extract the language and set it as active.
Here is some more great content about Transloco:
Top comments (0)