Git Product home page Git Product logo

angular-i18next's People

Contributors

efremovdy avatar evantrimboli avatar fshchudlo avatar jacobf7 avatar luca-peruzzo avatar prhc-marco avatar romanchuk avatar royling avatar shadizar128 avatar timebutt avatar wawyed avatar zilbuz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

angular-i18next's Issues

Trying to use the Pipe in submodules

Hi,
I have registered your module with forRoot() as you specify and it works in the parent component fine, but won't work in one of the subModules. Do I need to import the module again somewhere else?

I18NextService.loadLanguages calling down to i18next.loadNamespaces

Hi, thanks for the library.

I am trying to use the I18NextService.loadLanguages method in my app to load a new language on user request in my app. On doing so I see the following in my debug logs (in the browser console).

i18next::backendConnector: loaded namespace de for language en

On further investigation I see that the I18NextService.loadLanguages method actually calls down to i18next.loadNamespaces:

https://github.com/Romanchuk/angular-i18next/blob/master/src/I18NextService.ts#L95

I was wondering if this is an oversight or if I'm missing something? I'd be happy to update the code and submit a PR if it helps.

NativeScript with i18next - language pipe is not updating the text

I'm working on a project with NativeScript 6.4.1 and Angular 8.

I want to use the i18next library in my project: https://www.i18next.com/

Here is my sample repository: https://github.com/aubrey-fowler/i18nextTranslationsTest

Problem: When I change the language, the view is not updating the translation - it's always showing English. Why is it not showing the correct translation?

I followed to directions here to integrate the library with Angular: https://github.com/Romanchuk/angular-i18next

 npm install i18next --save
 npm install angular-i18next --save

Here is a code snippet:

export class ItemsComponent implements OnInit {

    constructor(@Inject(I18NEXT_SERVICE) private i18NextService: ITranslationService) {

        this.i18NextService.events.languageChanged.subscribe(lang => {
            // do something
            console.log(' i18NextService ', lang); //this code is called
        });

    }

    changeLang(lang: string) {
        this.i18NextService.changeLanguage(lang);
    }

    addLang(lang: string) {
        this.i18NextService.addResourceBundle(lang, 'translation', {
            "greeting": "Hej"
        }, true, false);
    }

}

Here is my view:

<ActionBar title="{{ 'greeting' | i18next }}"></ActionBar>

<StackLayout>

    <Label text="{{ 'greeting' | i18next }}"></Label>

    <Button text="en" (tap)="changeLang('en')"></Button>
    <Button text="fr" (tap)="changeLang('fr')"></Button>
    <Button text="nl" (tap)="changeLang('nl')"></Button>

    <Button text="add nl" (tap)="addLang('nl')"></Button>

</StackLayout>

Using multiple namespaces

I don't see an option to include multiple namespaces in a module. When I was using i18next in React I could simply do ['base', 'common', 'component'] to include three namespaces.

Is this possible with angular-i18next? Could it be?

i18n automatic translate (make target) angular9

I cannot create the document "messages.ru.xlf" with the "target" automatically.

I still have to add it manually.

my html with i18n:

<h1 i18n = "main header | Friendly welcoming message"> Welcome! </h1>

then I made the command: ng xi18n --i18n-locale ru --out-file locale / messages.ru.xlf

is there a way to automatically translate the html "welcome"?

because I don't want to add a target manually

this is just an example. later I will have a project with lots of language and text and it will not be possible to translate the whole .xlf document each time with each change and therefore each time we order:
ng xi18n --i18n-locale ru --out-file locale / messages.ru.xlf

can you help me?

Backend missing files prevents angular app from starting, when fallback should be applied

As per the issue listed at i18next/i18next-xhr-backend#261, if a file is missing, the i18next-xhr-backend issues an error message to the callback indicating the missing files.

The system would normally continue with a graceful fallback, but due to the handling by I18NextService in init the app initialization is rejected.

(err: any) => {
if (err) {
console.error(err);
reject(err);
} else {

When using this project in the app initialization as defined in the cookbook section of the README (https://github.com/Romanchuk/angular-i18next#initialize-i18next-before-angular-application), the reject prevents the angular app from initializing, and only a blank screen is presented.

Update peerDependency of i18next

Currently doing some Angular updates in our application and updated angular-i18next.

Seems like the specified peerDependency of i18next is not valid anymore.
We were using "i18next": "^11.6.0", and ran into build errors from angular-i18next.
Updating to the latest (19.4.3) fixed this.

Missing function overloading in ITranslationService

The translation method is missing one of it's forms where it accepts a default value.
From i18next we can see the definition of the TFunction as:

export interface TFunction {
// basic usage
<
TResult extends TFunctionResult = string,
TKeys extends TFunctionKeys = string,
TInterpolationMap extends object = StringMap
>(
key: TKeys | TKeys[],
options?: TOptions | string,
): TResult;
// overloaded usage
<
TResult extends TFunctionResult = string,
TKeys extends TFunctionKeys = string,
TInterpolationMap extends object = StringMap
>(
key: TKeys | TKeys[],
defaultValue?: string,
options?: TOptions | string,
): TResult;
}

Using with AOT builds

Hi!
Thank you for your efforts of integration i18next with Angular.

The documentation of this library says that AOT is supported. We are trying to use it with AOT build of our application and got an error:

image

Could you please add a short guide how to set it up?

IE11 Support

Great works for creating such a good module. It will be great if it supports IE11

Question: warning in the readme regarding [email protected]

There is a warning in the readme:

If you use "i18next-xhr-backend" plugin make sure it's version less than 3.0.0 (version 3.0.0 is not working properly)

Could you please provide more details? What's not working? I didn't see this message and installed 3.0.0. It seems to work, but maybe I'm missing something.

unexpected token

Hi,

I see some of my clients dying on the russian characters you have with the error "unexpected token". Can these be removed?

Unit Test Documentation

Hi @Romanchuk ,

Would you be able to provide documentation on how you would unit test a component using the i18next translation. I looked in the demo app repo but couldn't see any examples.

Do you mock the entire service and pipe?

Warning with Angular-18next with angular-cli

Hi,

Just wondering if you have came across this warning before ? The app still works with the warning but I wonder if there is a proper way to fix this warning.

WARNING in ./src/app/dashboard/dashboard.component.ts
102:277-296 "export 'ITranslationService' was not found in 'angular-i18next'
at HarmonyImportSpecifierDependency._getErrors (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:65:15)
at HarmonyImportSpecifierDependency.getWarnings (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/dependencies/HarmonyImportSpecifierDependency.js:39:15)
at Compilation.reportDependencyErrorsAndWarnings (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/Compilation.js:701:24)
at Compilation.finish (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/Compilation.js:559:9)
at applyPluginsParallel.err (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/Compiler.js:506:17)
at /Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/tapable/lib/Tapable.js:289:11
at _addModuleChain (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/Compilation.js:505:11)
at processModuleDependencies.err (/Volumes/Data/git-repo/sc-ols-live-reporting-ui/node_modules/webpack/lib/Compilation.js:475:14)
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)

Typing for I18NextFormatPipe only takes string?

We use the i18next formatter to format Date objects (and pass it other types) why did you only allow values to be strings? We clearly want number formatting - the examples from i18next show type detection in the formatter function configured...

export declare class I18NextFormatPipe implements PipeTransform {
private translateI18Next;
constructor(translateI18Next: ITranslationService);
transform(value: string, options: Object | string): string;
}

Angular 10

As soon as angular 10 releases:

  • Update angular deps
  • Raise up i18next dependecy to >= 19

changeLanguage not working in ionic(angular) 4

Hi here is what I do..

my app module

...

import { I18NextModule, ITranslationService, I18NEXT_SERVICE, I18NextLoadResult, defaultInterpolationFormat } from 'angular-i18next';
import { NgModule, APP_INITIALIZER, LOCALE_ID } from '@angular/core';
import XHR from 'i18next-xhr-backend';
import * as i18nextLanguageDetector from 'i18next-browser-languagedetector';

/*
 * Platform and Environment providers/directives/pipes
 */
const i18nextOptions = {
  lng: 'fr',
  whitelist: ['en', 'fr'],
  fallbackLng: 'en',
  debug: true, // set debug?
  returnEmptyString: false,
  ns: [
    'translation',
    'validation',
    'error'
  ],
  interpolation: {
    format: I18NextModule.interpolationFormat(defaultInterpolationFormat)
  },
  // backend plugin options
  backend: {
    loadPath: 'assets/locales/{{lng}}/{{lng}}.{{ns}}.json'
  },
  // lang detection plugin options
};

export function appInit(i18next: ITranslationService) {
  return () => {
    const promise: Promise<I18NextLoadResult> = i18next
      .use(XHR)
      .use(i18nextLanguageDetector)
      .init(i18nextOptions);
    return promise;
  };
}

export function localeIdFactory(i18next: ITranslationService)  {
  return i18next.language;
}

export const I18N_PROVIDERS = [
  {
    provide: APP_INITIALIZER,
    useFactory: appInit,
    deps: [I18NEXT_SERVICE],
    multi: true
  },
  {
    provide: LOCALE_ID,
    deps: [I18NEXT_SERVICE],
    useFactory: localeIdFactory
  },
];

firebase.initializeApp(environment.firebaseConfig);

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    IonicStorageModule.forRoot(),
    I18NextModule.forRoot(),
    AppRoutingModule,
    VirtualScrollerModule,
    FormsModule,
    ReactiveFormsModule,
    ComponentsModule,
  ],
  providers: [
    StatusBar,
    GooglePlus,
    SplashScreen,
    Camera,
    AppRate,
    Contacts,
    SocialSharing,
    Facebook,
    AppAvailability,
    I18N_PROVIDERS,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

IN my profile page I change language using i18next service my this...

selectLanguage(event) {
    i18next.changeLanguage(event.target.value, (err, t) => {
      console.log('err', t);
    })

  }

but when my drop down select the value language is not changing.. when I come back to profile page its changes.. but on home page its same .. so what's the problem is ??

I have used lazy load and in each module I have added I18NextModule.forRoot(), in providers.

please help :)

I18NextService.language is an empty string

If I have an initializer setup like this

 
const options = {
    whitelist: ['en', 'ru'],
    fallbackLng: 'en',
    lng: 'en',
    debug: true, // set debug?
    returnEmptyString: false,
    ns: [
    'translation',
    'validation',
    'error',

    // 'feature.rich_form'
    ]
}

export function AppInitializerFactory(i18next:  I18NextService) {
    return () => {
        const i18NextPromise: Promise<I18NextLoadResult> = i18next
        .init(options);

        return i18NextPromise;
    }
};

  export const I18N_PROVIDERS = [
    { provide: APP_INITIALIZER, useFactory: AppInitializerFactory, deps: [I18NEXT_SERVICE], multi: true },
    { provide: LOCALE_ID, deps: [I18NEXT_SERVICE], useFactory: localeIdFactory }
  ];

I get a value for I18NextService.language. However if I move the logic into a class then I get an empty string for I18NextService.language.

export class AppInitializer {
    constructor(
        private i18next: I18NextService) {}

    load()  {
            const i18NextPromise: Promise<I18NextLoadResult> = this.i18next
            .init(options);

            return i18NextPromise;
        }
}

export function AppInitializerFactory(initializer:  AppInitializer) {
    return () => initializer.load();
};


export const I18N_PROVIDERS = [
    AppInitializer,
    { provide: APP_INITIALIZER, useFactory: AppInitializerFactory, deps: [AppInitializer], multi: true },
    { provide: LOCALE_ID, deps: [I18NEXT_SERVICE], useFactory: localeIdFactory }
];

Any ideas why the language is an empty string when I move it into a class?

I18next pipe not available for components in common module

Hi @Romanchuk

I have the following NG modules in my application :

My Shared module
@NgModule ({ declarations : [ SomeCommonComponent ... ] , exports : [ SomeCommonComponent ... ] , imports : [ BrowserModule ] })

My Core module where I import the I18Next and my shared module above
@NgModule ({ imports : [ MySharedModule , I18NextModule.forRoot () ] , providers : [ CoreServices ... ] })

My application module
@NgModule ({ bootstrap : [ ApplicationComponent ] , imports : [ CoreModule ] , declarations : [ ApplicationComponent ] })

The problem I am having is that the i18next pipe is not available to my components in MySharedModule. Do I need to export the pipe or something?

Angular 8 RC4 - "export 'DOCUMENT' was not found in '@angular/platform-browser

When using the RC versions of Angular 8, I'm getting this error when building the application using angular-18next version 6.0.1.

ERROR in /node_modules/angular-i18next/fesm5/angular-i18next.js 748:63-71
"export 'DOCUMENT' was not found in '@angular/platform-browser'

Are changes required here to make this package work with the latest instalment of Angular?

For reference, these are the Angular dependencies I am currently building with:

Angular CLI: 8.0.0-rc.4
Node: 11.13.0
OS: darwin x64
Angular: 8.0.0-rc.4
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router, service-worker

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.800.0-rc.4
@angular-devkit/build-angular      0.800.0-rc.4
@angular-devkit/build-ng-packagr   0.800.0-rc.4
@angular-devkit/build-optimizer    0.800.0-rc.4
@angular-devkit/build-webpack      0.800.0-rc.4
@angular-devkit/core               8.0.0-rc.4
@angular-devkit/schematics         8.0.0-rc.4
@angular/cdk                       8.0.0-rc.1
@angular/http                      8.0.0-beta.10
@angular/material                  8.0.0-rc.1
@angular/pwa                       0.13.8
@ngtools/webpack                   8.0.0-rc.4
@schematics/angular                8.0.0-rc.4
@schematics/update                 0.800.0-rc.4
rxjs                               6.5.1
typescript                         3.4.5
webpack                            4.29.0

I18nextService.events.languageChanged is not triggered

When I change the language, the languageChanged event doesn't seem to be triggered.

I change the language like so:


    setLang(lang) {

    this.i18nextService.changeLanguage(lang).then(evt => {
      console.log("setLang", evt);
    });
  }

This changes the language, but the languageChanged event is not triggered. Here is how I listen for this event.

    this.i18nextService.events.languageChanged.subscribe(lng => {
      console.log("angular-i18next", lng);
    })

When I listen to the event on the underlying i18next implementation, I do get notified of the event:

    const i18next = i18n.default;

    ...

    i18next.on('languageChanged', (lng) => {
      console.log("i18next - languageChange", lng);
      console.log("this.i18n.events.languageChanged.getValue()", this.i18nextService.events.languageChanged.getValue());
    })

That last console.out learns me that the value on the languageChanged BehaviorSubject hasn't been set properly. These are the logs:

i18next - languageChange nl
this.i18n.events.languageChanged.getValue() null
setLang {err: undefined, t: ฦ’}

i18next::translator: missingKey

Hi,

I tried to follow the demo application but can't get any keys to translate. I have this in my component template:

{{ 'myname' | i18next }}

I have this in my console:
`

i18next::backendConnector: loaded namespace mynamespace for language en {
    "myname": "Scott"
}
i18next::translator: missingKey en mynamespace myname myname

Any idea why I can't get a simple translation to work?

Import Error: Module not found

Hi,
After install last version of package, when import it I get the following error:

"ERROR in ./node_modules/angular-i18next/angular-i18next.es5.js
Module not found: Error: Can't resolve 'i18next/index' in '/..node_modules/angular-i18next'"

My angular-cli.json,

"scripts": [
        "../node_modules/angular-i18next/es5/angular-i18next.js"
]

How can I solve this problem ?

Suggestion for doc fix

Hi,

import { I18NextPipe } from './I18NextPipe';

You have this in the example about "using it in your code" I think you want:

import { I18NextPipe } from 'angular-i18next';

This has bitten many devs here. Can you explain a bit more why we should inject the pipe vs the service into component controllers?

i18next for t.options not working anymore in 9.0.0

Translating t.options like this:

`{{ 'operation.editTarget' | i18nextCap: { target: 'control.title' | i18next } }}

was working in versions 7.0.0 and 8.0.1 - but does not work anymore in 9.0.0.

Note: we want to pass a translated text to the target variable of operation.editTarget.

Is this a regression, or is there now another way to do this?

Other versions:

  • angular 9
  • i18next: 19.3.1

Initialization with XHR Backend result in undefined Keys message

I am struggling with accessing the translation ressources from the backend. Using the pipe outputs an undefined message.
The debug message: i18next::translator: missingKey undefined translation test test
I used the pipe like:
<p>{{'test' | i18next}}</p>

When i use angular-18next without the backend property and directly insert ressources it works perfectly fine.
But since the XHR is async, i think this creates the problem.
The order of messages logged to console is:

  1. i18next::translator: missingKey undefined translation test test
  2. i18next::backendConnector: loaded namespace translation for language en
  3. i18next: initialized

So it first tries to find the key, which is not yet fetched from the backend, then it gets the translations and afterwards i see all my translations in the console. The markup still displays the translation key.

How can i tell the pipe to wait until translations are loaded, or what would be a better approach to get the translations from a backend server? Right now the server just returns the .json file on a request like "/locales/en".

I am using Google Chrome on Windows 10,

  • "angular-i18next": "^4.0.0-beta",
  • "angular": "^6.0.3",
  • "i18next": "^11.3.3",
  • "i18next-xhr-backend": "latest",

My Configuration in Angular 6:

import { Component, Inject } from '@angular/core';
import { I18NEXT_SERVICE, ITranslationService } from 'angular-i18next';
import Backend from 'i18next-xhr-backend';
import * as i18nextLanguageDetector from 'i18next-browser-languagedetector';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  constructor( @Inject(I18NEXT_SERVICE) private i18NextService: ITranslationService ){
    i18NextService
      .use(Backend)
      .use(i18nextLanguageDetector)
      .init({
        backend: {
          // path to post missing resources
          addPath: "http://localhost:4000/locales/{{lng}}/{{ns}}.missing.json",
          // jsonIndent to use when storing json files
          jsonIndent: 2,
          // path where resources get loaded from
          loadPath: "http://localhost:4000/locales/{{lng}}/{{ns}}.json"
        },
        whitelist: ['en'],
        fallbackLng: 'en',
        debug: true,
        returnEmptyString: false,
      });
  }
}

Function calls are not supported

When following the section Initialize i18next before angular application, I get the following error:

ERROR in Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 22:17 in the original .ts file), resolving symbol AppModule in /MY_APP/src/app/app.module.ts
    at positionalError (/MY_APP/node_modules/@angular/compiler/bundles/compiler.umd.js:25266:35)
    at simplifyInContext (/MY_APP/node_modules/@angular/compiler/bundles/compiler.umd.js:25109:27)
    at StaticReflector.simplify (/MY_APP/node_modules/@angular/compiler/bundles/compiler.umd.js:25123:13)
    at StaticReflector.annotations (/MY_APP/node_modules/@angular/compiler/bundles/compiler.umd.js:24553:41)
    at _getNgModuleMetadata (/MY_APP/node_modules/@angular/compiler-cli/src/ngtools_impl.js:138:31)
    at _extractLazyRoutesFromStaticModule (/MY_APP/node_modules/@angular/compiler-cli/src/ngtools_impl.js:109:26)
    at Object.listLazyRoutesOfModule (/MY_APP/node_modules/@angular/compiler-cli/src/ngtools_impl.js:53:22)
    at Function.NgTools_InternalApi_NG_2.listLazyRoutes (/MY_APP/node_modules/@angular/compiler-cli/src/ngtools_api.js:91:39)
    at AotPlugin._getLazyRoutesFromNgtools (/MY_APP/node_modules/@ngtools/webpack/src/plugin.js:207:44)
    at _donePromise.Promise.resolve.then.then.then.then.then (/MY_APP/node_modules/@ngtools/webpack/src/plugin.js:443:24)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

The error is in this piece:

    useFactory: (i18next: ITranslationService) => () => {
      return i18next.init();
    },

Is there a way to work around this and make this work with the last Angular versions?

Component testing

Hello Romanchuk!
Unfortunately, your example does not help me :/
Can you give some advice pls, what did I do wrong?

When I run my test file, I get 2 errors:
1.) NullInjectorError: No provider for InjectionToken I18NEXT_SERVICE!
2.) Error: The pipe 'i18next' could not be found!

And my Test file:

`export function appInit(i18next: ITranslationService) {
return () => {
const promise: Promise = i18next
.init({
debug: true,
lng: 'cimode'
});
return promise;
};
}

export function localeIdFactory(i18next: ITranslationService) {
return i18next.language;
}

export const I18N_PROVIDERS = [
{
provide: APP_INITIALIZER,
useFactory: appInit,
deps: [I18NEXT_SERVICE],
multi: true
},
{
provide: LOCALE_ID,
deps: [I18NEXT_SERVICE],
useFactory: localeIdFactory
},
];

describe('NavComponent', () => {
let component: NavComponent;
let fixture: ComponentFixture;

beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
BrowserModule,
UiElementsModule,
RouterTestingModule,
HttpClientModule,
BrowserAnimationsModule,
MatExpansionModule,
I18NextModule.forRoot()
],
declarations: [ NavComponent ],
providers: [
{ provide: 'environment', useValue: environment },
{ provide: UserManagerService, useClass: MockUserManagerService },
I18N_PROVIDERS
],
})
.compileComponents();
});`

warnings on init (with fix !)

Hi !

First of all, thanks for this repo ! I've been using i18next for my React projects and really wanted to use it for me Angular project as well !

I copied your code and found warnings after serving my Angular app :

i18next.js:22 i18next: hasLoadedNamespace: i18n.languages were undefined or empty undefined

and

i18next::translator: key "login-input_label_login" for languages "en" won't get resolved as namespace "translation" was not yet loaded This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!

I fixed it by adding lng: 'en' to the init of i18next and everything worked !

i18next.init({
  lng: 'en',
  whitelist: ['en', 'fr'],
  fallbackLng: 'en',
  debug: true,
  returnEmptyString: false,
  ns: ['translation', 'validation', 'error'],
  resources: {
    en: enTranslation,
    fr: frTranslation,
  },
});

Have a terrific day !

[Feature request] Make the pipe update the translation when the language changes

I use components with HTML like this:

<div>
  {{ 'tranlation_key' | i18next }}
</div>

The key gets translated on a component mount but it isn't retranslated when I change the language by calling:

// ...
constructor(
  @Inject(I18NEXT_SERVICE) private i18NextService: ITranslationService
) {
  setTimeout(() => {
    this.i18NextService.changeLanguage('es');
  }, 5000);
}
// ...

A retranslated text is shown only when the component is updated by another reason. I intuitively expect the i18next pipe to update the translation when the language changes like the async pipe does.

I'm not an expert in Angular, but as far as I know there is a way to force a component update from pipe.

Maybe there is another way to retranslate the components on language change? I really don't want to reload the whole page like in your demo, I consider it as user unfriendly.

BTW, this.i18NextService.events.languageChanged.subscribe works well in my components.

i18next escapes HTML special characters in substitutions by default

This is not a problem in angular-i18next. But I think you can improve the usage experience by considering this i18next feature in any way. It is a problem because Angular escapes special characters too which leads to double-escaping. For example, this code {{ 'greeting' | i18next: { name: '"Google"' } }} gives this string in browser Hello, &quot;Google&quot;!. You can mention this feature in the readme and offer/implement one of the solutions:

  • Disable the escaping globally in the i18next configuration:

    i18next.init({
      // ...,
      interpolation: {
        escapeValue: false,
      },
    });

    This is the best solution IMHO because dealing with a raw HTML in Angular is a rare case and one who deals with raw HTML would need to escape the substitutions manually anyway.

  • Disable the escaping in the pipe or/and in the service:

    i18next.t(key, {
      ...substitutions,
      interpolation: {
        escapeValue: false,
        ...substitutions.interpolation,
      },
    })
  • Disable the escaping in templates: greeting: 'Hello, {{- name}}!'

i18nextpipe.d.ts is not exported from angular-i18next

"@angular/core": "^9.1.5",
"angular-i18next": "^9.0.1",
"i18next": "^19.4.3",

Can`t build project

ERROR in Symbol I18NextPipe declared in .../node_modules/angular-i18next/i18nextpipe.d.ts is not exported from angular-i18next (import into ../libs/layer-components/src/lib/header/header.component.ts)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.