Using a SharedModule in Angular2: A Guide

I have a single Angular2 component that I need to utilize across multiple modules. To achieve this, I created a SharedModule as shown below:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {GenericComponent} from './generic/generic.component';
@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ GenericComponent ],
  exports:      [ GenericComponent ]
})
export class SharedModule { }

Subsequently, I included the SharedModule in various modules like so:

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {SharedModule} from './shared.module';
import { AppComponent } from './app.component';
@NgModule({
  imports:      [ BrowserModule, SharedModule ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap: [AppComponent]
})
export class AppModule { }

I also integrated the SharedModule into generic.module.ts similarly:

generic.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {SharedModule} from './shared.module';
@NgModule({
  imports:      [ BrowserModule, SharedModule ],
  declarations: [ //.. here I have added all the components that generic uses ]
})
export class GenericModule { }

However, upon attempting to use the generic component within other components of generic.module.ts, I encountered the following error:

Unexpected value 'undefined' imported by the module 'GenericModule'

Answer №1

Below is the code snippet from my application utilizing a shared module:

App module:

import { AboutModule } from './about/about.module';
import { SharedModule }   from './shared/shared.module';
import { Menubar, MenuItem } from 'primeng/primeng';

@NgModule({
    imports: [ BrowserModule, RouterModule.forRoot(appRoutes), SharedModule.forRoot(), 
               HomeModule ],
    declarations: [ AppComponent ],
    bootstrap: [ AppComponent ],
    providers: [ appRoutingProviders ]

}) 

export class AppModule {} 

The home module:

import { SharedModule }   from '../shared/shared.module';
import {routing} from './home.routing'


@NgModule({
    imports: [ SharedModule, routing],
    declarations: [ HomeComponent, LoginComponent, RegisterComponent, VerifyComponent, 
                   VerifyEmailComponent, ForgotComponent, ForgotVerifyComponent, 
                   ChangeComponent, ChallengeComponent, LogoutComponent ], 
    bootstrap: [ HomeComponent ],
    providers: [ ]

}) 

export class HomeModule {} 

Shared Module:

@NgModule({
  imports: [CommonModule, RouterModule, MenubarModule, GalleriaModule, InputTextModule, PanelModule, ButtonModule,
            DropdownModule, DialogModule, AccordionModule, CalendarModule, SelectButtonModule, CheckboxModule,
            ProgressBarModule, DataTableModule],
  declarations: [ ErrorMessagesComponent, FoodDashboardComponent ],
  exports: [ CommonModule, ReactiveFormsModule, HttpModule, RouterModule,
            MenubarModule, GalleriaModule, InputTextModule, PanelModule, ButtonModule, DropdownModule, DialogModule, AccordionModule, CalendarModule,
            SelectButtonModule, CheckboxModule, DataTableModule, ProgressBarModule, ErrorMessagesComponent, FoodDashboardComponent ]
})

export class SharedModule {
  //
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [SettingsService, AppMenuService, AuthorizationService, LoginService, RegisterService, ThemeService, ValidationService,
        NutritionixService, AuthGuardService, CalculationService, ChallengeService ]
    };
  }
}

In my application, I have extensively utilized the shared module in more than 20 modules. It has proven to be effective across various functionalities. Feel free to adapt it for your own usage.

Answer №2

It's important to note that BrowswerModule should not be used in the featureModule. Instead, make sure to utilize CommonModule for this purpose.

import { NgModule }      from '@angular/core';
import { CommonModule }        from '@angular/common';
import {SharedModule} from './shared.module';
@NgModule({
  imports:      [ CommonModule ,SharedModule ],
  declarations: [ //.. here I have added all the components that generic uses ],
  exports:      [ CommonModule]
})
export class GenericModule { }

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

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

Uncover the content of a base64 encoded string and convert it into

A JSON response has been linked on the user's request to retrieve an excel document. The structure of the response is as follows: { "format": // file extn ----only xls "docTitle": //file name "document" :// base 64 encoded data } The attem ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...

Elements recognized worldwide, Typescript, and a glitch specific to Safari?

Consider a scenario where you have a select element structured like this: <select id="Stooge" name="Stooge"> <option value="0">Moe</option> <option value="1">Larry</option> <option value="2">Curly</option ...

Uploading Files through Reactive Forms in Angular

I tried following a tutorial on integrating file upload functionality into my reactive form, which can be found at the following link: . However, I've encountered an issue where I'm getting an error message stating "this.onChange is not a functio ...

The content within the mat-card-content paragraph exceeds the boundaries of the mat-card container,

I recently began working with Angular Material and came across an issue. When I have a shorter text paragraph, it overflows the card. However, when I use a larger paragraph, the text wraps nicely. Here is the code snippet: <mat-card *ngFor="let s ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Distribute your SolidJS Typescript components on npm

Recently, I developed a SolidJS TypeScript UI component and successfully published it to the npm registry. The project structure is organized as follows: |-app |-index.html |-src |-index.tsx |-App.tsx |-utils |- ... |-com ...

Utilizing the relativeTo method within a guard across various feature modules

I am facing a challenge with two lazily loaded Feature Modules that have a similar flow consisting of Select, Review, and Confirm steps. I want to create a single Guard for the Review step that can navigate back to Select based on the current Module contex ...

What could be causing my Cypress 12.12 configuration file to be deemed incorrect when working with Angular 16?

I encountered an issue while executing npx cypress open: export default defineConfig({ | ^ 5 | e2e: { 6 | setupNodeEvents(on, config) { 7 | // implement node event listeners here 8 | }, Error Messag ...

Declare, condition, and output all in a single statement

Is there a method to condense the content inside the function below into a single line? I want to avoid declaring check. function Example { const check = this.readByUuidCheck(props) if (check) return this.readByUuid(check) } I am seeking ways to ...

Encountering an issue with importing mongoose models while trying to create a library

I've been working on creating a library of MongoDB models and helper classes to be shared as an npm module with the rest of my team. However, I'm facing an issue with the main code that I import from lib MongoConnector which processes configurati ...

What is the best way to incorporate audio playback while browsing files on an HTML5 webpage with TypeScript?

<input type="file" id="soundUrl" (change)="onAudioPlay()" /> <audio id="sound" controls></audio> This is the HTML code I'm working with, and I'm looking to trigger audio playback after a user selects an MP3 file using TypeScrip ...

Issue NG0203 encountered during material import attempt

I've been encountering an issue with importing material. Despite using code similar to the examples on material.angular.io, I keep running into the ""inject() must be called from an injection context..." error. My goal is to create a simple table ...

What is the method for ensuring TypeScript automatically detects the existence of a property when an object is statically defined?

In my software, I have an interface that serves as a base for other types. To simplify things for this discussion, let's focus on one specific aspect. This interface includes an optional method called getColor. I am creating an object that implements ...

Generic type input being accepted

I am trying to work with a basic generic class: export class MyType<T>{} In the directive class, I want to create an @Input field that should be of type MyType: @Input field MyType<>; However, my code editor is showing an error that MyType& ...

Transforming JSON data into XML using Angular 7

It turns out the xml2js npm package I was using doesn't support converting JSON to XML, which is exactly what I need for my API that communicates with an application only accepting XML format. In my service file shipment.service.ts import { Injecta ...

Whenever I try to retrieve a value using the key from ModelBindingContext.ValueProvider.GetValue(key

When working with AngularJS to manipulate a complex parent object with different behaviors for its children server-side, I encountered an issue while implementing the CreateModel function as suggested in this answer. The problem arises when any call to bin ...

Using LINQ with ngFor in Angular 6

Within the component.ts, I extract 15 different lookup list values and assign each one to a list, which is then bound to the corresponding <select> element in the HTML. This process functions correctly. Is there a method to streamline this code for ...