Search code examples
angulardependency-injectionangular7

Angular - importing and using a custom module - getting StaticInjector error


I have an Angular 7 project with a multi-project folder structure. I've created a module for each project. For this example, let's assume I have two projects, a main and sub.

My main-project.module.ts:

//main-project.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MainProjectComponent } from './main-project.component';
import { SubProjectModule } from '../../../sub-project/src/app/sub-project.module';
import { routing } from './main-project-routing.module';

@NgModule({
  declarations: [
    MainProjectComponent
  ],
  imports: [
    BrowserModule,
    routing,
    SubProjectModule
  ],
  providers: [],
  bootstrap: [MainProjectComponent]
})
export class MainProjectModule { }

My sub-project.module.ts:

import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { routing } from "./sub-project-routes.routes";
import { StatusComponent } from "./components/status.component";
import { SubProjectService } from "./services/sub-project.service";

@NgModule({
  declarations: [
    SubProjectComponent,
    StatusComponent
  ],
  imports: [
    BrowserModule,
    routing,
  ],
  providers: [SubProjectService],
  bootstrap: [SubProjectComponent]
})
export class SubProjectModule { }

From my understanding, if I import the SubProjectModule in MainProjectModule, I shouldn't have to add services or components that are uses specifically by the SubProject in the MainProject module file - is this correct?

Right now, if I try to create the SubProjectComponent (which uses the StatusComponent declared in the declarations section of SubProjectModule), I get the following error:

StaticInjectorError(MainProjectModule)[StatusComponent -> SubProjectComponent]: No provider for SubProjectComponent!

Here is my SubProjectComponent template:

<h2>This is the SubProjectComponent page.</h2>
<status></status> <!--'status' is the html selector for the StatusComponent-->

I recently upgraded an old Angular 2 project to Angular 7 so restructuring hasn't been too smooth. What exactly am I doing wrong?


Solution

  • In order to use components from SubProjectModule you would need to export those components.

    @NgModule({
       declarations: [
          SubProjectComponent,
          StatusComponent
       ],
       imports: [
          BrowserModule,
          routing,
       ],
       exports: [
          SubProjectComponent,
          StatusComponent
       ],
       providers: [SubProjectService],
       bootstrap: [SubProjectComponent]
    })
    export class SubProjectModule { }