Search code examples
angularlocalizationangular7code-translationngx-translate

Need to translate words in .ts file of angular-7 application for localization of app


I have to localize the angular-7 application. For that we already created the localizationModule which impports all required dependencies from '@ngx-translate/core';. Also I have imported the userService in which selected language will be set for application translation. I have translated all the html pages but the messages which are written in .ts file needs to be converted. I am not getting any way to achieve this. Can anyone help me to get out of this?


Solution

  • You have to use the TranslateService from @ngx-translate/core. You have two ways:

    • translate.instant with would just translate the word to the defined language directly.
    • translate.get which get the value from an observable.

    Here a little example how to use it:

    import { TranslateService } from '@ngx-translate/core';
    
    yourTranslatedText : string;
    yourTranslatedObservableText : string;
    
    constructor(
      private translateService: TranslateService,
    ) {
       yourTranslatedText = this.translateService.instant('your.key.string'); 
       this.translateService.get('your.key.string').subscribe((translatedString) => {
          yourTranslatedObservableText = translatedString;
       });
    }
    

    Note that you can pass an Array of keys so you can translate all the words you want at once.