Home > Net >  How to route to sub component in angular
How to route to sub component in angular

Time:06-08

I am working on an angular app that has parent and sub components structure. I am having issues with navigating to the sub structures.

The main routes are working fine, the issue now is navigating to the sub components.

This is the sample folder structure for the application.

enter image description here

This is the (notices) main folder routing file

enter image description here

This is the root routing file

enter image description here

So what I want is to be able to navigate to

Notices -> notices-details ( the sub folder of notices ) and to other files as well.

CodePudding user response:

Your (notices) main folder routing file should be like this

import{NgModule}from@angular/core';
import{Routes,RouterModule}from'@angular/router';
import{Public Notices Page}from'./public-notices.page';


const routes: Routes = [
  {
    path:'',
    component:PublicNoticesPage, children: [
        {
            path:'notices-list',
            loadChildren:()=>import('./ notices-list/notices-list.module').then(m=>m.NoticesListPageModule)
        },
        {
            path:'notice-categories',
            loadChildren:()=>import('./ notice-categories/notice-categories.module').then(m=>m.NoticeCategories PageModule)
        },
        {
            path:'notice-comments',
            oadChildren()=>import('./ notice-comments/notice-comments.module .then(m=>n.Notice Comments PageModule)
        },
        {
            path:'notices-nearby',
            loadChildren:()=>import('./ notices-nearby/notices-nearby.module').then(m=>m.Notices NearbyPageModule)
        }
    ]
  }
];

CodePudding user response:

Routing and Lazy Loading

Minimal example with lazy loading of a child module:

AppModule:

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot([
      {
        path: 'one',
        loadChildren: () =>
          import('./one/one.module').then((m) => m.OneModule),
      },
    ]),
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

App template:

<button routerLink="one">ONE</button>
<router-outlet></router-outlet>

OneModule:

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild([

      {
        path: '', component: OneComponent,
        children: [
          {path: 'two', component: TwoComponent}
        ]
      }
    ])
  ],
  declarations: [OneComponent, TwoComponent]
})
export class OneModule { }

One Template:

<p>one works!</p>
<button routerLink="two">TWO</button>
<router-outlet></router-outlet>

You could (but really shouldn't) nest more modules to be lazy loaded. You want to keep your architecture as flat as possible. So a module per feature, lazy loaded from the AppModule, is plenty enough.

Here's a Stackblitz for you to try it out.

  • Related