Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular uses wrong router-outlet

I have a problem with Angular routing. I have main app routing module and sub module with its own routing module and router-outlet but routes defined in this submodule are shown using root router outlet and not the child one.

My folder structure:

My code listings

app-routing.module.ts

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' }
];

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

app.component.html

<router-outlet></router-outlet>

home-routing.module.ts

const routes: Routes = [
  { path: '', component: LandingPageComponent},
  { path: 'register', component: RegisterComponent },
  { path: 'login', component: LoginComponent }
];

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

home.component.html

...
<div class="inner cover">
  <router-outlet></router-outlet>
</div>
...

That's what I get when I use empty path - it opens home component properly.

enter image description here

But when i enter /register i get plain html from login.component.html without template in home.component.html file

enter image description here

EDIT

I added name to child outlet

<router-outlet name="home"></router-outlet>

Changed route names to:

const routes: Routes = [
  { path: '', component: LandingPageComponent, outlet: 'home'},
  { path: 'register', component: RegisterComponent, outlet: 'home' },
  { path: 'login', component: LoginComponent, outlet: 'home' }
];

Now I got that error:

enter image description here

EDIT 2

I try to access those routes in 2 ways: A link(which may be incorrect):

<a routerLink="/login">Log In</a></li>

Or typing manually:

localhost:4200/login
like image 316
Bartosz Gajda Avatar asked Sep 03 '26 04:09

Bartosz Gajda


1 Answers

In Angular 2, router outlets can be named:

<router-outlet>
    <router-outlet name="children"></router-outlet>
</router-outlet>

App:

const routes: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' }
];

Home:

const routes: Routes = [
  { path: '', component: LandingPageComponent, outlet: 'children'},
  { path: 'register', component: RegisterComponent, outlet: 'children' },
  { path: 'login', component: LoginComponent, outlet: 'children' }
];

You can even define child routes:

const routes: Routes = [
  { path: '', 
    component: HomeComponent, 
    pathMatch: 'full', children: [
      { path: '', component: LandingPageComponent, outlet: 'children'},
      { path: 'register', component: RegisterComponent, outlet: 'children' },
      { path: 'login', component: LoginComponent, outlet: 'children' }
    ] 
   }
];

http://onehungrymind.com/named-router-outlets-in-angular-2/

like image 130
Pop-A-Stash Avatar answered Sep 05 '26 16:09

Pop-A-Stash