Search code examples
javascriptangularangular7angular7-router

The child row is not accessible in child component using Angular 7


I just started to learn Angular 7 and I'm a little confused about routing. I created a route configuration in app-routing module and child row in message-routing module.

I expect these routes:

/
/message
/message/inbox
/message/new
/about

But routes inside messageComponent are not accessible:

Cannot match any routes. URL Segment: 'message/new'

These are my configurations:

app-routing.module.ts:

const routes: Routes = [
  {
    path: '',
    component: HomeComponent
  },
  {
    path: 'message',
    component: MessageComponent
  },
  {
    path: 'about',
    component: AboutComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

message-routing.module.ts:

const routes: Routes = [
  {
    path: 'message',
    component: MessageComponent,
    children: [
      {
        path: '',
        component: InboxComponent
      },
      {
        path: 'new',
        component: NewComponent
      }
    ]
  }
];

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

app.module.ts:

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

And this is my folder structure:

Folder structure of my Angular app


Solution

  • I solved the problem by Adding Inbox and New components to the message-routing.module.ts. I'm not sure if here is the best place to add them but this solved the problem.

    message-routing.module.ts:

    const routes: Routes = [
      {
        path: 'message',
        component: MessageComponent,
        children: [
          {
            path: '',
            component: InboxComponent
          },
          {
            path: 'new',
            component: NewComponent
          }
        ]
      }
    ];
    
    @NgModule({
      declarations: [InboxComponent, NewComponent],
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule]
    })