Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Child routes load parent component

I am trying to get my routing to work in my Angular 2 application.

Here is the code I am using in the app.routes.ts file

export const ROUTES: Routes = [
  { path: '',      component: PublicComponent, data: { title: 'Heroes List' } },
  { path: 'home',  component: PublicComponent },
  { path: 'admin',  component: PrivateComponent, children: [
    { path: '', component: PrivateComponent },
    { path: 'account-settings', component: AccountSettingsComponent, children: [
      { path: '', component: UserInformationComponent},
      { path: 'user-information', component: UserInformationComponent},
      { path: 'companys-information', component: CompanysInformationComponent}
    ] },
  ] },
  { path: '**',    component: NoContentComponent },
];

Every time I try to navigate to one of the child routes it loads up the parent route.

So lets say for example I go to:-

http://localhost:4200/#/admin

It pulls in the correct component PrivateComponent.

But when I navigate to:-

http://localhost:4200/#/admin/account-settings

Or any children of the account settings it loads up the PrivateComponent and not the AccountSettingsComponent or UserInformationComponent as stated in the code you can see above.

Am I missing something in my code to get this to work?

The application was generated using Angular CLI.

Thank you in advance.

like image 254
Tony Hensler Avatar asked Jun 17 '17 11:06

Tony Hensler


People also ask

Can we pass data from child to parent in Angular?

The Angular documentation says "The @Output() decorator in a child component or directive lets data flow from the child to the parent." This is exactly what we want.

How do you pass data from parent component to child component?

To let Angular know that a property in a child component or directive can receive its value from its parent component we must use the @Input() decorator in the said child. The @Input() decorator allows data to be input into the child component from a parent component.


1 Answers

You will not need another <router-outlet> in the component.

Instead of defining a component in the parent route have a root path in children that points to the parent, like so:

{ path: 'admin', children: [
    { path: '', component: PrivateComponent },
    { path: 'account-settings', children: [
        { path: '', component: AccountSettingsComponent},
        { path: 'user-information', component: UserInformationComponent},
        { path: 'companys-information', component: CompanysInformationComponent}
    ] },
] },

On the other hand I can see the benefit of using an additional <router-outlet> if you want to display a common element for each child routes i.e. a header.

like image 133
slajma Avatar answered Oct 21 '22 01:10

slajma