core icon indicating copy to clipboard operation
core copied to clipboard

How to handle import TranslateModule.forChild in module when moving to standalone components

Open LoganDupont opened this issue 1 year ago • 2 comments

Hi,

I was wondering how you should handle an import of TranslateModule.forChild in your module when moving to standalone components? This was used because we only wanted to load the translations when navigating to a route path which lazy loads this module. Currently I have an NX project with multiple libs and each lib has his module and own assets folder with the translation files. The libs are used by one or multiple apps and in my app I have a project. json file which contains this in my target.build.options.assets

{
"glob": "**/*",
"input": "libs/i18n/assets",
"output": "/assets/shared/i18n"
},
{
"glob": "*",
"input": "libs/feat1/src/assets/i18n",
"output": "/assets/modules/feat1/i18n"
},

example:

import {HttpBackend} from '@angular/common/http';
import {NgModule} from '@angular/core';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';



function translateLoaderFactory(httpBackend: HttpBackend) {
	return new CustomMultiTranslateHttpLoader(httpBackend, ['assets/modules/feat1/i18n/', 'assets/shared/i18n/']);
}

@NgModule({
	imports: [
		TranslateModule.forChild({
			loader: {
				provide: TranslateLoader,
				useFactory: translateLoaderFactory,
				deps: [HttpBackend]
			},
			isolate: true
		})
	],
	providers: [TranslationLoaderResolver]
})
export default class Feat1Module {}

In the component which has been transformed to a standalone component I added TranslateModule to the imports of the @Component decorator.

LoganDupont avatar Oct 27 '23 15:10 LoganDupont

@LoganDupont you can do something along these lines:

  1. in main app configuration importProvidersFrom(TranslateModule.forRoot({...}), +other modules)
  2. In your lazy loaded routes (where you previously needed .forChild { path: 'somePath' component: MyStandaloneComponent, providers: [importProvidersFrom(TranslateModule.forChild({ extend: true }))] }

anatolie-darii avatar Nov 14 '23 17:11 anatolie-darii

Hi, Same problem for me but @LoganDupont explanation did not solve it because each standalone components (previously a module) have to load its own translation from a separate file via lazy-loading. So, it's not possible to do it in main app config. I tried to do it in routes definition via "providers" parameter and "importProvidersFrom" but translations are not loaded for the targeted component.

zazics avatar Dec 08 '23 08:12 zazics