Home > Back-end >  router-outlet' is not a known element
router-outlet' is not a known element

Time:10-02

Looks like it's a very common issue. I tried taking help from other answers but I'm still getting this error. Here is my code:

products-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LaptopComponent } from './laptop/laptop.component';
import { MobileComponent } from './mobile/mobile.component';
import { ProductsComponent } from './products.component';

const routes: Routes = [
  {
    path: 'products',
    component: ProductsComponent,
    children: [
      { path: 'laptops', component: LaptopComponent },
      { path: 'mobiles', component: MobileComponent },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class ProductsRoutingModule {}

products.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LaptopComponent } from './laptop/laptop.component';
import { MobileComponent } from './mobile/mobile.component';
import { ProductsRoutingModule } from './products-routing.module';

@NgModule({
  imports: [CommonModule, ProductsRoutingModule],
  declarations: [LaptopComponent, MobileComponent],
})
export class ProductsModule {}

products.component.html

<h1>Products</h1>
<ul>
  <li routerLink="laptops">Laptops</li>
  <li routerLink="mobiles">Mobiles</li>
</ul>

<router-outlet></router-outlet>

and here is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { ProductsModule } from './products/products.module';
import { AppRoutingModule } from './app-routing.module';

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

Can you please point out my mistake. Here I've the stackblitz of the same.

CodePudding user response:

This problem is occurring because your ProductsComponent is not declared by any module. The problem will go away if you add it to the declarations in products.module.ts:

@NgModule({
  imports: [CommonModule, ProductsRoutingModule],
  declarations: [ProductsComponent, LaptopComponent, MobileComponent],
})
export class ProductsModule {}
  • Related