Search code examples
angularrouter-outlet

Angular Components not known inside router outlet


Context

I created an angular app with this configuration:

? What name would you like to use for the new workspace and initial project? test-route
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS   [ https://sass-lang.com/documentation/syntax#scss

I created two component, that are realy simple

    import { Component } from '@angular/core';
    
    @Component({
        selector: 'app-first',
        templateUrl: './first.component.html',
    })
    export class FirstComponent { }

Inside the html there is juste a simple text

First Component

The seconde component is basicly the same but i replaced First by Second.

I created a route for my first component.

    const routes: Routes = [
      { path: 'first-component', component: FirstComponent },
    ];

What i want to do

Then i want to add my second component inside the html of first one

    First Component
    <app-second></app-second>

And i also add my second component inside my app.module.ts

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

Problem

When i do that i have an error

error NG8001: 'app-second' is not a known element:

  1. If 'app-second' is an Angular component, then verify that it is part of this module.
  2. If 'app-second' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

I also tried to add the second component directly inside my app.component.html and there no errors. How can i use my custom components from my routes ?

Here is a exemple on stackblitz


Solution

  • There is no error if you also add FirstComponent to your declarations array in your AppModule

    declarations: [AppComponent, SecondeComponent, FirstComponent],