Include module A in module B, even though module A has already included module B's Angular

Currently, I am facing an issue with circular dependencies between two modules - User and Product. The User Module has already imported the Product Module to utilize the ProductListComponent. Now, I need to import/use the UserListComponent from the User Module in the Product Module. However, attempting to import the User Module into the Product Module is resulting in a circular dependency error. Is there a solution that allows me to access all modules within each other while maintaining logic in their respective places and reusing features?

One approach I considered was creating a common/Shared Module that imports all other modules into it. Then, each module would import this Shared Module, theoretically making all modules available to one another. Unfortunately, implementing this strategy also triggers a circular dependency error, proving it to be invalid.

Product Module

@NgModule({
  declarations: [ProductListComponent],
  imports: [
    CommonModule,
    ProductRoutingModule,
  ], exports: [ProductListComponent]
})
export class ProductModule { }

User Module

@NgModule({
  declarations: [UserListComponent],
  imports: [
    CommonModule,
    UserRoutingModule,
    ProductModule
  ], exports: []
})
export class UserModule { }

Attempted Solution using a shared module

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    UserModule,
    ProductModule
  ], exports: []
})
export class SharedModule { }

Product Module

@NgModule({
  declarations: [ProductListComponent],
  imports: [
    CommonModule,
    ProductRoutingModule,
    SharedModule
  ], exports: [ProductListComponent]
})
export class ProductModule { }

User Module

@NgModule({
  declarations: [UserListComponent],
  imports: [
    CommonModule,
    UserRoutingModule,
    SharedModule
  ], exports: []
})
export class UserModule { }

I am seeking guidance on how to efficiently share all modules across the application to prevent code repetition and maintain a design that is agnostic towards specific applications.

Answer №1

    In order to utilize a shared module in your app.module, make sure to register it as shown below:

    App Module



  @NgModule({
      declarations: [],
      imports: [
        SharedModule
      ], exports: []
    })
    export class AppModule { }

    The shared module should be structured like this:


  @NgModule({
      declarations: [ProductListComponent, UserListComponent],
      imports: [
        CommonModule,
        UserModule,
        ProductModule
      ], exports: []
    })
    export class SharedModule { }

 Now you have access to all the modules.
 Avoid importing modules multiple times.

Answer №2

To ensure proper functionality, make sure to include the SharedModule in the main app module's file.

Answer №3

Ahmad, it is advised against importing every single module into the shared module. The shared module serves the purpose of housing components, directives, and other elements that are required across multiple modules such as headers, footers, and sidebars.

In your scenario, it would be more beneficial to create a common component or directive for functionalities that are needed in various components for reusability. This common element can then be placed in the shared module and imported into the FeatureModule (User/Product in this case).

  • If the functionality is not common, only export the specific component (ProductListComponent) and import its module (ProductModule) into the necessary module (UserModule), or vice versa (UserListComponent in ProductModule).

Importing every module into each module defeats the purpose of using Angular. It also has a negative impact on optimization!

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

Angular's AsyncValidatorFn is triggered by the onblur event and does not work with keypress events

I'm currently working with the latest version of Angular and I'm attempting to implement a custom validation for checking a code through a RestAPI. The example below is functional, but it doesn't trigger on keypress events; it only activates ...

Adjust an IntervalObservable's interval by incorporating a variable

I've encountered an issue with a component that needs to run code at regular intervals without pausing. I'm currently using an IntervalObservable and need to adjust the interval dynamically. While I can change the variable value using the setTime ...

The expected function is being executed, yet none of the inner functions are invoked

Currently, I am working on unit tests for an Angular application using Jasmine and Karma. One particular unit test involves opening a modal, changing values in a form, and saving them. Everything goes smoothly until it reaches the promise inside the open() ...

Error thrown due to syntax issues in react.d.ts declaration file in TypeScript

Currently, I am attempting to integrate react with typescript in my project. However, typescript is generating syntax errors for the react.d.ts file sourced from Github: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/react The encountered ...

What is the best way to include an object in a document before sending it back?

I am facing a challenge that involves retrieving data from Firestore using angularfire. Once I fetch a collection, I need to iterate through each document in the collection and then make a separate request to Firestore to get additional document values. Th ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Navigating with Gatsby Link and leveraging TypeScript

I am currently utilizing Gatsby Link with TypeScript and I am looking to pass parameters to a linked component from the source component. The documentation provided by Gatsby states the following: Sometimes you’ll want to pass data from the source pag ...

Retrieve the previous value of the selection change with the Mat Select function

In my current project, I have a form with a mat-select dropdown. Whenever the user makes a selection, a dialog pops up to confirm the choice. However, I am facing an issue: The selectionChange() event is triggered when the value changes and provides the n ...

Here is a way to retrieve the name of a ref object stored in an array using Vue.js 3 and Typescript

I have a Form, with various fields that I want to get the value of using v-model and assign them to ref objects. In order to populate my FormData object with this data, I require both the name and the value of the ref objects. Unfortunately, I am struggli ...

Update the Material V4 Style ts file to the latest version, Material V5

I am currently in the process of upgrading from material v4 to v5. The problem I am encountering is related to a styles.ts file that I used to import into my component. Initially, the beginning of the class looked like this: import { defaultFont, prima ...

Clicking on an Angular routerLink that points to the current route does not function unless the page is re

Currently, I am working on an E-commerce project. In the shop page, when a user clicks on the "View More" button for a product, I redirect them to the product details page with the specific product id. <a [routerLink]="['/product-details' ...

Encountering the error message "Subscribe is not a function in Jasmine" while

Encountering an issue where I am receiving an error stating "subscribe is not a function" in Angular unit testing. Here is the call that I have implemented in my component: this.myService.employees.subscribe(emp => this.emp = emp); Despite creating a ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

The Angular 7 template falls short of occupying the entire page

I am currently working on converting an HTML page into my Angular project. While it functions correctly in the HTML version, it does not fill up the entire page when transferred to Angular. You can view an example of this issue on StackBlitz at the followi ...

Tips for creating a responsive swiper slider in an Angular project

In my Angular project, I am using a swiper slider with 4 items in desktop view. However, I would like to display only 1 item in the mobile view. You can see the code at this link: https://stackblitz.com/edit/ngx-swiper-wrapper-demo-h9egdh?file=app/app.com ...

React Testing Library - Screen debug feature yields results that may vary from what is displayed in the

Greetings to all who come across this message. I have developed a tic-tac-toe game in typescript & redux with a 3x3 grid, and now I am facing some challenges while trying to write unit tests for it. Consider the following game board layout where X represen ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

Create the Angular 6 service within the directory "e2e/app"

After upgrading my Angular 4 to 6, I attempted the following command: ng generate service security/security However, the service was generated under the "e2e/app" folder instead of the expected "src/app" location. Below is an excerpt from my angular.json ...

Strategies for reducing the number of ngIf statements in Angular's template

I'm seeking advice on how to avoid using multiple *ngIf in templates. For instance, in a component's template, depending on the route, I need to display various elements like so: <div *ngIf="route == 'page1'">Title for page 1< ...

Using an object-key value array with *ngFor in Angular 7

I am trying to populate an array of objects in a table, but the changes are not being displayed as expected. <ng-container *ngFor="let file of err_data "> <tr> <td>{{file.details.commodity_name}}</td> <t ...