Home > Blockchain >  How does angular distinguish router-outlet tags anchored in multiple components
How does angular distinguish router-outlet tags anchored in multiple components

Time:11-14

In app.component.html we have a < router-outlet > which it will dynamically load other modules and components and views.

but if we have a 2nd component (imported in a different module) with its own < router-outlet >

how does angular distinguish between the 2 existing router outlets for example, how does angular know

"router1" (containing path:"/url-1" path:"/url-2") gets loaded in app.component.html. and "router2" (containing path:"/url-3" path:"/url-4") gets loaded in secondComp.component.html

when both app.componen.html and secondComp.component.html have this tag specifically < router-outlet >

how does angular know which router definition needs to be used/loaded by x component.

Just for learning purposes

CodePudding user response:

Angular concept of routing is define that in app.component.html which is global routing means application default UI or parent route is render from it. & in our routing file we are distinguish path for parent & child path of routing let say as example:

app.component.html

<div>
    <router-outlet></router-outlet>
</div>

app.module.ts

in imports section

RouterModule.forRoot([
      { path: '', component: LoginComponent, pathMatch: 'full' },
      { path: 'Login', component: LoginComponent, canActivate: [AuthGuardService] },
      { path: 'Home', loadChildren: () => import('./librarymanagement/librarymanagement.module').then(m => m.LibraryManagementModule) },

])

So all parent level routes are render at parent level [Login, Home] so this both route treat as parent route.

now in Home route load feature module called LibraryManagementModule.

const routes: Routes = [
  {
    path: '', component: LibraryManagementComponent,
    children: [{ path: 'Dashboard', component: DashbordComponent, canActivate: [AuthGuardService] },
      { path: 'country', component: CountryComponent, canActivate: [AuthGuardService] },
  }

Now child route loads its child called [ Dashboard,country ] inside Home route. as child of RouterModule.

RouterModule.forChild(routes)

So all route treat as tree to indicate the specific identifier to call. inside LibraryManagementModule bootstrap component is LibraryManagementComponent which contains

LibraryManagement.component.html

<div>
        <router-outlet></router-outlet>
</div>
  • Related