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

How to link a selection choice to an option using Angular 13

Can anyone provide guidance on how to bind data with a select option in Angular? I've tried multiple approaches but haven't been successful in getting the data to display in the options. Any assistance would be greatly appreciated. Thank you in a ...

When updating data, the cursor in Angular 2 textboxes tends to move to the end of the

I have specific restrictions in the name field that I am attempting to validate using a directive. Within the directive, I am utilizing a regular expression to verify a valid name and then updating the textbox with the valid name using valueAccessor.writeV ...

What is the best way to retrieve a value from an array of objects containing both objects and strings in TypeScript?

Consider this scenario with an array: const testData = [ { properties: { number: 1, name: 'haha' } , second: 'this type'}, ['one', 'two', 'three'], ]; The goal is to access the value of 'second&ap ...

Issue encountered with passport-local in TypeScript: Unable to utilize 'new' with an expression that does not have a call or construct signature

Currently, I am attempting to implement the passport-local package in TypeScript (version 2.0.0RC); however, a compiler error has arisen: Error TS2351: It is not possible to use 'new' with an expression lacking a call or construct signature. ...

Tips for ensuring radiobuttons are defaulted to unchecked within a shared form group in Angular 2 and beyond

The radio buttons are linked to data from the database (Web-API). Below are my complete code snippets: component.html <!-- list of Questions --> <div formArrayName="questions"> <!-- <div *ngFor="let que of Questions; let ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

Discover how to set up lazy loaded child routes within a parent route that is also loaded lazily in Angular 2

Struggling to implement lazy loading for my app has been a series of challenges. I successfully implemented lazy loading for the main route, /admin, but now I am facing issues while adding another route, /admin/login. This is what I tried: admin-router.m ...

Issues with the visibility of inlined styles within the Angular component library

After developing a custom library with components for an Angular 4 application, I encountered an issue where the CSS styling from the components was not being applied when using them in an application. Although the functionality worked fine, the visual asp ...

Are there any solutions to refresh a page by clicking a button in next.js?

I am currently learning how to work with next.js and I'm facing an issue where I need to reload my page to make a new API request. As a beginner, I'm not sure how to achieve this. I've tried a few methods but none of them seem to work. Below ...

Head to the "/unauthorised" route in Angular while maintaining the current URL intact

I have a security guard that directs the user to an "/unauthorised" route when they do not have permission to access the current page (which could be any page). @Injectable() export class PermissionGuard implements CanActivate { constructor(private reado ...

Angular2: Maintaining a continuous connection for a child component to receive input from the parent component post onInit

I'm currently working on integrating an error message component into another parent component. The child component, which displays the error message, has an input attribute that the parent component uses to pass the error message. However, I've e ...

Tips for Validating Radio Buttons in Angular Reactive Forms and Displaying Error Messages upon Submission

Objective: Ensure that the radio buttons are mandatory. Challenge: The element mat-error and its content are being displayed immediately, even before the form is submitted. It should only show up when the user tries to submit the form. I attempted to use ...

Error: Loki cannot be used as a constructor

Can anyone assist me in understanding why this code is not functioning correctly? Here's what my index.ts file in Hapi.js looks like: import { Server, Request, ResponseToolkit } from '@hapi/hapi'; import * as Loki from 'lokijs'; ...

What's New with Material 3 in Angular 17?

Even though I've taken the time to read all of the documentation at https://github.com/material-components/material-web/blob/main/docs/quick-start.md, I'm still struggling to figure out how to incorporate this into my Angular 17 project. I went ...

What is the proper way to utilize a service within a parent component?

I need assistance with setting up inheritance between Child and Parent components. I am looking to utilize a service in the Parent component, but I have encountered an issue. When attempting to input the service in the Parent constructor like this: expor ...

Utilizing Angular 2 for transforming JSON data into Angular classes

I have been working through the Angular2 getting started guide to kickstart my own application development. So far, I have managed to retrieve JSON objects from a local file and display them in angular2 templates. However, the challenge arises when the str ...

Is there a way to automatically validate v-forms inside a v-data-table when the page loads?

In my data entry form, I have utilized a v-data-table with each column containing a v-form and v-text-field for direct value updates. My goal is to validate all fields upon page load to identify any incorrect data inputs. However, I am facing challenges in ...

Converting CommonJS default exports into named exports / Unable to load ES module

I've encountered an issue while creating a Discord bot with discord.js using TypeScript. When attempting to run the resulting JavaScript code, I'm facing an error that states: import { Client, FriendlyError, SQLiteProvider } from 'discord.js ...

There seems to be a mismatch in this Typescript function overloading - None of the over

Currently, I am in the process of developing a function that invokes another function with enums as accepted parameters. The return type from this function varies depending on the value passed. Both the function being called (b) and the calling function (a ...

Encountered error: Unable to locate module - Path 'fs' not found in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib' within newly generated Chakra application

Started by creating the app using yarn create react-app chakra-ts --template @chakra-ui/typescript. Next, added dotenv with yarn add dotenv Inserted the following code block into App.tsx as per the instructions from dotenv documentation: import * as dote ...