Search code examples
angularroutesrouter-outlet

Angular 11 - RouterModule - 'router-outlet' is not a known element


I’m new in Angular, at the moment I working on routing. I run into an issue using sub routes in a component. The routerLink aren’t rendered as link in the component. If I use the router-outlet the app crashes.

Using the router-outlet I got the following error message:

    src/app/gardening/gardening/gardening.component.html:5:1 - error NG8001: 'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

5 <router-outlet></router-outlet>
  ~~~~~~~~~~~~~~~

  src/app/gardening/gardening/gardening.component.ts:5:16
    5   templateUrl: './gardening.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component GardeningComponent.

I googled the error message, the solution was always a missing import of the RouterModule in the module. I already imported the RouterModule.

This is my module.ts

@NgModule({
declarations: [GardeningComponent, DemogardenComponent],
imports: [
CommonModule, RouterModule
],
exports:[GardeningComponent, DemogardenComponent]

})
export class GardeningModule { }

This is my app.module.ts

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

What’s wrong, what is missed?

If you like, you can check the code in my repository on github as well: SimpleRouting


Solution

  • I don't see the exact same errors you mention, but I see other problems that have to do with missing imports.

    Since you have separate modules for Home and Gardening, you will also need to import them into your app.module.ts file:

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        AppRoutingModule,   
        GardeningModule,    // <------
        HomeModule          // <------
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

    Your code works fine after these two small changes. (working StackBlitz)