Using Angular2: Implementing a single module across multiple modules

Let's delve into an example using the ng2-translate plugin.

I have a main module called AppModule, along with child modules named TopPanelModule and PagesModule.


The ng2-translate is configured for the AppModule.

@NgModule({
  imports: [TranslateModule.forRoot({
    provide: TranslateLoader,
    useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
    deps: [Http]
  })],
  exports: []
})
export class AppModule {
  constructor(translateService: TranslateService) {    
  }
}

In the AppComponent, I set languages and define basic configuration for the TranslateModule.

@Component(...)
export class AppComponent {
  constructor(translateService: TranslateService) {
    translateService.addLangs(["en", "fr"]);
    translateService.setDefaultLang('fr');

    const browserLang = 'fr';
    translateService.use(browserLang.match(/en|fr/) ? browserLang : 'en');    
  }
}

However, when attempting to utilize the TranslateModule in the components of children modules - TopPanelComponent and PagesComponent, it doesn't function properly. Errors like pipe not existing or translation missing occur.


To address this issue, I created a separate module called MyTranslateModule, configured the TranslateModule within it, and then utilized this module in both the PagesModule and TopPanelModule.

@NgModule({
  imports: [TranslateModule.forRoot({
    provide: TranslateLoader,
    useFactory: (http: Http) => new TranslateStaticLoader(http, '/assets/i18n', '.json'),
    deps: [Http]
  })],
  exports: [TranslateModule]
})
export class MyTranslateModule {
  constructor(translateService: TranslateService) {
    translateService.addLangs(["en", "fr"]);
    translateService.setDefaultLang('fr');

    const browserLang = 'fr';
    translateService.use(browserLang.match(/en|fr/) ? browserLang : 'en');

    console.log('AdminTrModule: calling');
  }
}

and

@NgModule({
  imports: [MyTranslateModule]
})
export class PagesModule{

}

@NgModule({
  imports: [MyTranslateModule]
})
export class TopPanelModule{

}

This was a crucial step. It now works as intended! Though, there might be a concern regarding the creation of two instances of the TranslateModule. In case I change the language in the TopComponent by invoking translateService.use('en'), it only affects the language in the TopPanelModule, not the PagesModule.

Answer №1

To ensure proper functionality, it is necessary to establish a forRoot function within the 'MyTranslateModule' module.

export class MyTranslateModule {

static forRoot(): ModuleWithProviders {
    return {
      ngModule: MyTranslateModule ,
      providers: [TranslateService,TRANSLATION_PROVIDERS]
    };
  }

}

Subsequently, import MyTranslateModule into appModule by following the steps below:

@NgModule({
  bootstrap: [App],
  declarations: [
    App
  ],
  imports: [ // Import Angular's modules
    BrowserModule,
    MyTranslateModule.forRoot(),
    PagesModule,
    TopPanelModule
  ],
  providers: [ // Expose our Services and Providers into Angular's dependency ]
})

By doing so, the translate service will be established as a singleton instance throughout the application.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Resolved error: Angular 'title' identifier is undefined. The 'Movie[]' array does not have this member

Attempting to fetch data from the backend using Angular services. After reading the Angular docs, it was mentioned that interfaces should be used when sending requests somewhere It should look something like this: return this.http.get<Movie[]>(th ...

Communicating Data Between Controllers in Node.js

Within my PlantsController, I extract the Plants using the following method: function getAll() { const plants= HttpRequestPromise.get(config.ApiURL+'allPlants', config.head); return plants; } export class PlantsController { ... public ...

Troubleshoot Angular2 modules efficiently using source mapping features

Is there a way to debug Angular2 module code using TypeScript source mapping in the browser? After installing my project with the "npm install" command following the steps in https://angular.io/guide/quickstart, I noticed that while source mapping is ava ...

Is it possible for an Interface's property to be a type that contains an array?

As I dive into the Angular code, I encountered a peculiar type for a property within an Interface named 'Origin' that has left me perplexed. Here's the snippet: export interface Origin { areaNum?: number; open?: { [key: stri ...

Unlock the Power of Angular: Crafting a Filterable TreeView Table

Seeking to create a treeview table with sorting using Angular 6 and PrimeNG. While PrimeNG's TreeTable comes close, I am in need of a global search filter to easily search within nodes. I attempted to use ng-treetable, but unfortunately it did not wo ...

Jest is simulating a third-party library, yet it is persistently attempting to reach

Here's a function I have: export type SendMessageParameters = { chatInstance?: ChatSession, // ... other parameters ... }; const sendMessageFunction = async ({ chatInstance, // ... other parameters ... }: SendMessageParameters): Promise<vo ...

To modify the color of text in a mat-list-option item

Using the mat-selection-list component, I have set up a list of contacts displayed through mat-list-option: https://i.sstatic.net/ri4lP.png Currently, the background-color changes when I click on a specific contact-name (e.g. Graeme Swan), and it remains ...

Angular 2+ seems to be failing to detect and update changes in variables within the template

I have a component that includes rendering the user's name from the profile object. The corresponding part of the template looks like this: <button mat-button [matMenuTriggerFor]="userMenu" *ngIf="isAuthenticated()"> {{profile?.name} ...

Implementing HTTPS Signed Certificates with IIS on Express for Production Environments

When it comes to managing API (HTTPS) certs in a development environment compared to production in an Express application running on a Node.js/Angular setup deployed to Windows IIS, the process can be a bit confusing. While proxy rewrites have been suggest ...

Why is my input field value not getting set by Angular's patchValue function

I've been attempting to populate an input field using the form group with patchValue(), but for some reason, the input remains empty. Here's a snippet of my code... component.html <form [formGroup]="createStoreForm" (ngSubmit)="createStor ...

The project graph creation for NX has encountered a setback and was unable to be completed. The worker has halted with exit

I've encountered an issue with my Angular project while using nx. Upon running npm install, I received the following error: > NX Nx Daemon was not able to compute the project graph. Log file with the error: ...\node_modules\.cache ...

Bring in properties from a separate file in Vue3

Currently, I am utilizing Vue3 along with the options API. Within my setup, there are various Vue components that rely on a shared prop defined as: exercise: { type: Object as PropType<Exercise>, required: true, }, To streamline this pro ...

Mixing a static class factory method with an instance method: a guide

After introducing an instance method addField in the code snippet below, I encountered an issue with the Typescript compiler flagging errors related to the static factory methods withError and withSuccess: The error message states: 'Property ' ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...

The tsconfig.json file does not support the path specified as "@types"

Having set up multiple absolute paths for my Next.js application, I encounter an issue where importing a component from the absolute path results in something like "../componentName" instead of "@components/componentName" when I am inside another folder. T ...

Is there a way to use openapi-generator with typescript-angular to generate just a module within an existing Angular project instead of creating a separate package?

Currently, I am utilizing the openapi-generator tool specifically for typescript-angular. Although I have been able to successfully generate an Angular module along with all its components, it results in a separate npm package. While I acknowledge the ad ...

Mastering the integration of NestJS with Redis for microservices

Currently, I am diving into the world of nestjs microservices. I am curious, what commands are available for me to use? const pattern = { cmd: 'get' }; this.client.send<any>(pattern, data) Additionally, how do I go about retrieving data ...

What is the correct way to declare the mongoose _id in a TypeScript interface?

I have a question about utilizing Mongoose and TypeScript using the interface+class+schema approach. When it comes to storing the _id field, what is the best method? I understand that the database stores it as a bson ObjectID. However, I've come acr ...

Error message for invalid form control not displayed when value is assigned to form control in Angular

I am currently working with this editor: <div id="editor"></div> which sets its value to a form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)` <div *ngIf="FrmGroup.get('name').inv ...

Utilizing NGRX reducers with a common state object

Looking for a solution with two reducers: export function reducer1(state: State = initialState,: Actions1.Actions1); export function reducer2(state: State = initialState,: Actions2.Actions1); What I want is for both reducers to affect the same state objec ...