user

Shilpa

3 Mar 2022

How to translate Angular application easily?

Angular

I am using latest ANGULAR 13 version and want to translate all the text written on my landing page to be translated in different languages chosen by readers.

I want support of French, German, and English (UK).

Here is my code sample, 

Library: free translate from NPM

npm i free-translate
const { translate } = require('free-translate');

(async () => {
 const translatedText = await translate('Hello World', { from: 'en', to: 'ja' });
 console.log(translatedText); // こんにちは世界
})();

But this is not much accurate, All translators are not 100% accurate because of grammar and masculine/feminine translations, but if I can achieve at least 95%, I am good with it! 

I have around 780-800 lines on the page. How do I convert the lines automatically or manually and show on base of user's language selection?

 

Comments

Rakshit

5 Mar 2022

Best Answer

best answer

I believe ngx-translate library will make your work easy. Online translators are not 100% accurate. I recommend one thing, If you want to convert your text to Spanish, contact someone who speaks spanish, german, french (any of them) or find a freelancer translator to convert your text.  They knows feminine vs masculine version of items.

Add npm package to your project using below command.

npm install @ngx-translate/core @ngx-translate/http-loader rxjs --save

Update your app.module.ts imports with below lines,

// import ngx-translate and the http loader
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
...
imports: [
	...,
		TranslateModule.forRoot({
 loader: {
 provide: TranslateLoader,
 useFactory: HttpLoaderFactory,
 deps: [HttpClient]
 }
 })
]
})

Add below code to your app.component.ts

...
constructor(private translate: TranslateService) {
 translate.setDefaultLang('en');
}

Add below code to Your app.component.html

<div>
 <h1>Translation demo</h1>
 <p>This is a simple demonstration app for ngx-translate</p>
</div>

Add a new file Inside your assets/i18n/en.json

{
 "demo.title": "Translation demo",
 "demo.text": "This is a simple demonstration app for ngx-translate"
}

Update your html markup as given below:

<div>
 <h1>{{ 'demo.title' | translate }}</h1>

 <!-- translation: translation pipe -->
 <p>{{ 'demo.text' | translate }}</p>

 <!-- translation: directive (key as attribute)-->
 <p [translate]="'demo.text'"></p>

 <!-- translation: directive (key as content of element) -->
 <p translate>demo.text</p>
</div>

Your output:

To learn and explore this library more, you can visit here.

Reference: website | github | npm

Shilpa

6 Mar 2022

github

Such a amazing explanation , I will try it for sure. Thank you.

© 2024 Copyrights reserved for web-brackets.com