Glains
Glains

Reputation: 2863

Angular 2 Router: Navigating to other components

Given the root routing module

const appRoutes: Routes = [
    {
        path: '',
        component: HomeComponent,
        children: [
            {
                path: 'users',
                loadChildren: './pages/users/users.module#UsersModule'
            }
        ]
    },
    {path: '', redirectTo: '', pathMatch: 'full'},
    {path: '**', redirectTo: '/login'}
];

export const appRouting: ModuleWithProviders = RouterModule.forRoot(appRoutes);

and the users routing module

const usersRoutes: Routes = [
    {
        path: '', component: UsersComponent,
        children: [
            {path: 'admittances', component: AdmittancesComponent},
            {path: 'admittance/:id', component: AdmittanceDetailComponent}
        ]
    }
];

export const usersRouting: ModuleWithProviders = RouterModule.forChild(usersRoutes);

i want to navigate from the AdmittancesComponent to the AdmittanceDetailComponent.

But, instead of using

this._router.navigate(['admittance', id]); // ERROR

i rather have to use

this._router.navigate(['users/admittance', id]); // WORKS

Can somebody explain why the first example is not working and why the second one fixes it?

Upvotes: 3

Views: 16358

Answers (2)

Ionut Botizan
Ionut Botizan

Reputation: 34

It's pretty simple The appRoutes is the main route , the users route is a child of your Main Route . Since you defined the name of the path in your appRoutes as 'users' , that's going to be your first url parameter so domain.com/users/childRoutes ...

Now as you have defined the child called admitance thats going to be prefixed by your parent Route users / so domain.com/users/admitance

It would have worked the first statement if you would have defined the route 'admitance' in your appRoutes

Upvotes: 0

DeborahK
DeborahK

Reputation: 60518

The following link is from the Angular documentation: https://angular.io/guide/router#relative-navigation

For relative routing using the .navigate, you need syntax like this:

this.router.navigate([crisis.id], { relativeTo: this.route });

Upvotes: 6

Related Questions