freetoplay
freetoplay

Reputation: 697

Angular 2 child routing

I am trying to figure out why my child route is not being found:

So I have a router that looks something like this:

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './about.component';
import { AboutTestComponent } from './about-test.component';
import { AboutSectionComponent } from './about-section.component';

const aboutRoutes: Routes = [
  {
    path: 'about',
    component: AboutSectionComponent,
    children: [
      {
        path: '',
        component: AboutComponent
      },
      {
        path: 'test',
        component: AboutTestComponent
      }
    ]
  }
];

export const aboutRouting: ModuleWithProviders = RouterModule.forChild(aboutRoutes);

In my about-section.component.html, I have the following mark-up:

<!-- some layout stuff here -->
<router-outlet></router-outlet>
<!-- more layout stuff -->
<button routerLink="/test"></button> <!-- I want to load the AboutTestComponent in the router outlet tags when I click on it -->

I want to be able to load the AboutTestComponent in the router-outlet of about-section.component.html because I want to reuse the HTML layout. Right now when I land onto the "about" route, I get the expected AboutComponent, but when I click on the button trying to navigate to the "test" route, I get a 404. Is there a way to make the "test" route accessible using the way I am doing it now? If not, what would be a good way of approaching this problem?

Upvotes: 0

Views: 145

Answers (1)

Philipp Kief
Philipp Kief

Reputation: 8613

I think this is only possible if you navigate to about/test with the following button:

<button routerLink="test"></button

I deleted the / before the test so it is a relative route.

If you now click on the button it will navigate to about/test and the router loads the AboutTestComponent into the <router-outlet> of the parent.

You can also solve it with an absolute route:

<button routerLink="/about/test"></button>

Upvotes: 1

Related Questions