0

I am using ng2-translate node package to implement translations in an Angular SPA application.

Following the instruction found at https://www.npmjs.com/package/ng2-translate (see Section #3 Define Translations), I defined the translations in one of the components as follows:

import { Component, } from '@angular/core';
import { TranslateService } from 'ng2-translate';


@Component({
    selector: 'home',
    templateUrl: './home.component.html'
})
export class HomeComponent  {


    constructor(private translate: TranslateService) {


        this.translate.setTranslation('en', {
            "HELLO": "Hello World from TranslateServiceLand"
        }, true);

        this.translate.setTranslation('fr', {
            "HELLO": "Bonjour tout le moonde d'TranslateServiceLand"
        }, true);
    }
}

This is however not working. Can someone please provide me with an example?

Subash
  • 7,098
  • 7
  • 44
  • 70
UncleZen
  • 289
  • 1
  • 4
  • 22

1 Answers1

1

Use Latest version ngx-translate/core

Actually setTranslation() is used for manually sets a object of translation for given language.

* @param lang
 * @param translations
 * @param shouldMerge
 */
setTranslation(lang: string, translations: Object, shouldMerge?: boolean): void;

Create i18n folder in your component folder

-componentfolder
 -i18nfolder
 -component.html
 -component.ts

component.ts

import { TranslateService } from '@ngx-translate/core';

        @Component({
            selector: 'home',
            templateUrl: './home.component.html'
        })

        export class HomeComponent  {

        constructor(translate: TranslateService) { }

         changeLanguage(lang) {
            this.translate.use(lang);
            let i18n = require(`./i18n/${lang}.json`);

            this.translate.setTranslation(lang, i18n, true);
          }
        }

component.html looks like

<ul class="dropdown-menu" role="menu">
                  <li>
                      <a class="dropdown-item" (click)="changeLanguage('en')">{{"Language.english" | translate}}</a>
                  </li>
                  <li>
                      <a class="dropdown-item"(click)="changeLanguage('es')">{{"Language.spanish" | translate}}</a>
                  </li>
</ul>

Hoping, you know how to create json files in i18n folder.

k11k2
  • 2,036
  • 2
  • 22
  • 36
  • I don't see any difference to the authors post to be honest. Key focus here is the function `setTranslation`, not HOW it is loaded. How would that make a difference if he defines it himself or if it comes from a json file? – Daniel Stephens Oct 05 '20 at 14:00