Search code examples
angularmodulereusability

Angular 2 Reusing Components with Shared Modules


I am trying to reduce redundant code in my application by consolidating components, used in multiple modules, into a shared module. I was following the Angular Post, https://angular.io/docs/ts/latest/guide/ngmodule.html#!#shared-module. It appears that I am missing a step because the application hangs when I make the described changes.

I have created two plunkers, one without Shared Module and a second plunker after the changes have been made. The initial code can be found at this link; https://plnkr.co/edit/VrEe5S54rEkKipuGLsQs?p=info

I then made the following changes.

  1. Created Shared Module (See code below)
  2. Added PageNotFoundComponent to SharedModule
  3. Updated app.module.ts

    a. Commented out FormsModule

    b. Commented out PageNotFoundComponent

    c. Imported SharedModule

  4. Updated app-routing.module.ts

    a. Commented out PageNotFoundComponent

Note that I tried to keep it simple by not adding too many components to the shared module and by not using shared module everywhere that it could have been used.

The Plunker with these changes can be found at this link; https://plnkr.co/edit/I4ArEQTniO7MJtfzpBWl?p=info

The code for the Shared Module is as follows:

import { NgModule }            from '@angular/core';
import { CommonModule }        from '@angular/common';
import { FormsModule }         from '@angular/forms';

import { PageNotFoundComponent }     from './not-found.component';

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

Appreciate any thoughts on what steps I am missing or what I am doing wrong.


Solution

  • The error is:

    Error loading https://run.plnkr.co/5Q7FuGzCTzE1DQOa/app/shared/not-
    found.component.ts as "./not-found.component" from 
    https://run.plnkr.co/5Q7FuGzCTzE1DQOa/app/shared/shared.module.ts
    

    So shared.module.ts is in the 'app/shared' folder, but it's trying to load the not-found.component from the same directory.

    Looking at your plunker, the not-found.component is in the 'app' folder.

    I believe you need to move the not-found component to the 'app/shared' folder.