Angular universal + @ngx-translate

Pieterjan De Clippel
2 min readNov 3, 2023

This guide is a sequel to this story

Refactoring the project

We need to split up the AppModule in a seperate browser/server module

  • Install ngx-translate
npm i @ngx-translate/core@13 @ngx-translate/http-loader@6

Copy the file app.module.ts as app.browser.module.ts and make the following changes

ClientApp/src/app/app.browser.module.ts

Now instead of bootstrapping the appmodule, we need to bootstrap this module:

ClientApp/src/main.ts

Adding ngx-translate

Import the TranslateModule into the AppBrowserModule like this:

ClientApp/src/app/app.browser.module.ts

As you can see, we’re using the TranslateHttpLoader here.

Import the TranslateModule into the AppServerModule like this:

ClientApp/src/app/app.server.module.ts
translate-json-loader.ts

This loader just pulls the json from your translation files and returns it as an object.

Don’t forget the app.module.ts

ClientApp/src/app/app.module.ts

Create translation files

src/assets/i18n/en.json
src/assets/i18n/nl.json

We still have to turn on resolveJsonModule

Now let’s show this message in the AppComponent:

The english message is rendered in the application

Change language

Now listen to the queryparams and call the TranslateService to change the language:

Now add 2 links to the toolbar to change the langqueryparameter

At last let’s make the link texts visible. Add the following scss

app.component.scss

Build the project

In case you disabled the BootModuleBuilder, run the following command manually:

npm run build:ssr

Success:

You can view the changes in this commit

--

--