2

Can someone tell how can I separately define routes for multiple root components in an Angular6 + angular-cli project?

Currently, I have two root components AppComponent and LoginComponent and I am doing this to load these:

index.html

<body>
  <app-root></app-root>
  <app-login></app-login>
</body>

app.module.ts

@NgModule({
    ...
    bootstrap: [AppComponent, LoginComponent]
})

I have two queries:

  1. How can I define routes for the second root component
  2. How can I optionally load any root component depending on the routes?

Example: If I go to /login or /login/conf1 only LoginComponent should be loaded. For other routes AppComponent

Surprisingly, there are no tutorials about multiple root component on the web or at least I couldn't find one.

My use case for two components: Link

dasfdsa
  • 7,102
  • 8
  • 51
  • 93

2 Answers2

-1

you should leave AppComponent as is, and create another component to deal with routes

you should have AppComponent, LoginComponent and AnotherOneComponent

in app.module.ts

@ngModule({
   imports: [
     RouterModule.forRoot(routes)
   ]
})

export const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent
  },
  {
    path: '**',
    component: AnotherOneComponent
  }
];

in app.component.html

<router-outlet></router-outlet>

if you want to handle sth like

/login/conf1

you'll be need to define child routes

Damian Pioś
  • 473
  • 2
  • 5
-1
  1. If you want child routes for a route you can do the following:

    export const routes: Routes = [ { path: 'login', component: LoginComponent, children: [ { path: 'one', component: SomeComponent}, { path: 'two', component: SomeOtherComponent } ] } ];

  2. If you want to dynamically load a component based on the route you can inject the Router module in the app.component.ts file

constructor(private router: Router){}

and then in the html:

`
<app-login *ngIf="router.url != '/login' ></app-login>
`
Iulian Cucoanis
  • 195
  • 2
  • 6
  • Thanks but it doesnt answer the question. I am trying to have to root componets. Like AppComponent1 and AppCompoent2 – dasfdsa Jul 03 '18 at 13:01