Ranjith Varatharajan
Ranjith Varatharajan

Reputation: 1694

Dynamically load translation file for specific project

Scenario: I have a shared module which has ngx-translate and this shared module can be used in two or more different projects, each has it's own translation file. When this translator shared module is hooked up with a project, it should load only the project specific en.json not all.

So the shared module assets folder structure

assets
|--i18n
|----project1
|------en.json
|----project2
|------en.json

I'll pass the query whether the project is project1 or project2 from app.module.ts as shown below

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    SharedModule.forRoot('Project1'),
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

And I also get that value in my shared module, below is my shared module code

@NgModule({
    declarations: [ ],
    imports: [
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: httpTranslateLoader,
                deps: [HttpClient]
            }
        })
    ],
    providers: [],
    exports: [TranslateModule]
})
export class SharedModule {
    static forChild(project:string): ModuleWithProviders<any> {
        console.log(project); //this consoles the project but fails the build, I'm stuck here
        return {
            ngModule: SharedModule,
            providers: [ ]
        }
    }
}

export function httpTranslateLoader(http: HttpClient) {
    return new TranslateHttpLoader(http);
}

so based on the project i need to load only the en.json which is in the project folder in assets. Any suggestions would be appreciated.

Upvotes: 0

Views: 544

Answers (1)

Francesco
Francesco

Reputation: 10820

Could you save the path to your translation specific files in a JSON Object in the environment file?

If so, each project would have its own path pointing to the proper translation file.

// environments/environment.ts
export const globalEnv = {
  projectName: "my_projectId"
};

Upvotes: 1

Related Questions