I have Angular 8
application. I have divided my app into different modules.
I am trying to load the HomeComponent present inside HomeModule on the root url ('/
')
app.component.html
<app-header></app-header>
<router-outlet></router-outlet>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './module/common/header/header.component';
import { HomeModule } from './module/home/home/home.module';
//& so on.
@NgModule({
declarations: [
AppComponent,
LogoComponent,
MenuComponent,
SearchComponent,
SignComponent,
HeaderComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HomeModule,
UserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.routing.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './module/home/home/home.component';
import { HomeModule } from './module/home/home/home.module';
const routes: Routes = [
{ path : '', component : HomeComponent, loadChildren: ()=>
import('../app/module/home/home.module').then(mod => mod.HomeModule)}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
home.module.ts
import { NgModule } from "@angular/core";
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home/home.component';
@NgModule({
declarations:
[
HomeComponent
],
imports: [
CommonModule,
HomeRoutingModule
],
exports: [
HomeComponent
],
providers: []
})
export class HomeModule { }
But when running the application, it is throwing the below error.
Component HomeComponent is not part of any NgModule or the module has not been imported into your module
What is causing this error?
Thanks!
you made a mistake in app.routing.ts
const routes: Routes = [ { path : '', component : HomeComponent, loadChildren: ()=> import('../app/module/home/home.module').then(mod => mod.HomeModule)} ];
The correct code should be:
const routes: Routes = [
{ path : '', loadChildren: ()=> import('../app/module/home/home.module').then(mod => mod.HomeModule)}
];
Then create a home.routing.ts and code like this way:
const routes: Routes = [
{ path : '', component : HomeComponent }
];
As you don't need to use it in any other module and it obviously shouldn't, remove HomeComponent from exports:
exports: [ HomeComponent ],
this code should be removed.
Explanation: Because in app component, we load the module lazily, not component. So, we shouldn't specify homeComponent in app.routing.ts.
Every module should have own routing. As home is a module, it should have a home.routing.ts and we need to specify which route it should go when loading home module. So, we specify the homecomponent in home routing.