Using NG2-Translate with Ionic2: not clear where the i18n/ folder should be located

Having a look at https://ionicframework.com/docs/v2/resources/ng2-translate/;

It says that: “By default this will look for your translation json files in i18n/”; but where should be located that folder? should it be under [project]\src\ or anywhere else?

@nyluje I created the folder /src/assets/i18n/ (it will be sent to /www/assets/i18n/ with ionic serve). Then I import the module with:

export function createTranslateLoader(http: Http): TranslateStaticLoader {
	return new TranslateStaticLoader(http, './assets/i18n', '.json');
}

@NgModule({
	imports: TranslateModule.forRoot({ 
		provide: TranslateLoader,
		useFactory: createTranslateLoader,
		deps: [Http]
	}),
	exports: TranslateModule,
})

hey @nyluje how did you load the pipes:[TranslatePipe] . with the latest RC0 i get error

@arsene123 I don’t think you need to load the pipe in RC0/RC1 explicitly, you just load the module (TranslateModule) with @NgModule (the pipe is loaded with the module).

The docs are here: https://github.com/ocombe/ng2-translate

(Look for If you use a custom TranslateLoader and use AoT compiling or Ionic 2… in the docs)

i wan to translate some data for AlertController

I created a github project to test the implementation: https://github.com/nyluje/ionic2_ng2-translate_implementation-test/

On Ionic serve, I get issue for not finding “Http” but I don’t know which import should be added really.

This doesn t work, here is what I did, based on your input and the existing documentation:

In the “app.module.ts” file:

import { NgModule } from '@angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { TranslateModule } from 'ng2-translate/ng2-translate';

export function createTranslateLoader(http: Http) {
    return new TranslateStaticLoader(http, './assets/i18n', '.json');
}


@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    IonicModule.forRoot(MyApp),
    TranslateModule.forRoot({provide: TranslateLoader,
      useFactory: (createTranslateLoader),
      deps: [Http]})
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: []
})
export class AppModule {}

Then in the src/pages/home/ home.ts:
import { Component } from ‘@angular/core’;

import { NavController } from 'ionic-angular';

import {TranslateService} from 'ng2-translate';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,public translate: TranslateService) {
        translate.setDefaultLang('en');
        translate.use('en');
  }

}

And src/pages/home/ home.html has a line: <p>{{home|translate}}</p>
`

import {Http} from ‘@angular/http’

@arsene123, import {Http} from '@angular/http' helps a little bit.

Now @lucasbasquerotto the 2 error messages are:

Cannot find name ‘TranslateStaticLoader’ for the function createTransalteLoader in “app.module.ts”

And

Cannot find name ‘TranslateLoader’ in the TranslateModule.forRoot as well in “app.module.ts”

@nyluje You have to import those in your module, just like with Http (I think your editor/IDE shows errors in the code, in this case):

import { TranslateLoader, TranslateModule, TranslateStaticLoader } from 'ng2-translate/ng2-translate';

@arsene123 To use it in your code (not in the pipe) you must use the TranslateService. I created a TranslationService to wrap the ng2-translate TranslateService:

import { Injectable } from '@angular/core';
import { LangChangeEvent, TranslateService } from 'ng2-translate/ng2-translate';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class TranslationService {
    constructor(
		private translateService: TranslateService
	) { }

    setDefaultLang(lang: string) {
		return this.translateService.setDefaultLang(lang);
	}
	
    use(lang: string): Observable<any> {
		return this.translateService.use(lang);
	}
	
    getCurrentLang(): string {
		return this.translateService.currentLang;
	}

	onLangChange(): Promise<LangChangeEvent> {
		return new Promise((resolve, reject) => {
			this.translateService.onLangChange.first().subscribe(
				event => resolve(event),
				error => reject(error)
			);
		});
	}
	
    instant(key: string | Array<string>, interpolateParams?: Object): string | any {
		let result =  key && this.translateService.instant(key, interpolateParams);
		result = (result !== key) ? result : '';
		
		if (key && !result) {
			console.error(`[not translated key]::${key}`);
		}

		return result;
	}
}

I retrieve the translation with the instant method (I could use the get method, but it returns an observable I normally prefer retrieving the data immediately).

To make sure that the traslations were already loaded in the AppComponent I set the root page only after the onLangChange return:

ngOnInit() {
	return this.defineLang().then(
		() => this.defineRootPage()
	);
}

private defineLang(): Promise<any> {
	let promise = this.translationService.onLangChange();

	let  userLang = 'en';
	this.translationService.setDefaultLang(userLang);
	this.translationService.use(userLang);

	return promise;
}

defineRootPage() {
    // define the root page here...
}

otherwise the instant method could not return the translation.

In the docs you can read more about the TranslateService: https://github.com/ocombe/ng2-translate

(Look for API)

1 Like

Thanks, just time to try it

Thanks @lucasbasquerotto & @arsene123

You got any working solution on this?

Read the updated guide: https://ionicframework.com/docs//resources/ng2-translate/

1 Like

4 posts were split to a new topic: Ngx-translate: outputs key instead of translated string