简体   繁体   中英

Angular2 RouterLink in child component is expecting route to be defined in parent component

I am using two components one is parent component and the second one is child component in its template. Now in child component I have defined a route and placed a router outlet and a router link in child component's template. So that when I click on this link it should update the contents at its own router outlet but its giving the following error and is searching for a route to be defined in its parent component:

EXCEPTION: Component "ParentComponent" has no route config.in[['ChildRoute'] in ChildComponent@2: 26]

The components are:

@Component({
    selector: 'parent-cmp',
    template: '<child-cmp></child-cmp>',
    directives: [
        ROUTER_DIRECTIVES,
        ChildComponent
    ]
})
export class ParentComponent { }

@Component({
    selector: 'child-cmp',
    template: `
        <router-outlet></router-outlet>
        <a [routerLink]="['ChildRoute']">Edit</a>
    `,
    directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
    { path: '/edit', name: 'ChildRoute', component: ChildEditComponent }
])
export class ChildComponent { }

Assuming the imports are correct, I haven't mentioned here for brevity.

When you make the link to child route defines the route father before

try this,

<a [routerLink]="['ParentRoute','ChildRoute']">Edit</a>

To access child route from parent, always use

<a [routerLink]=['ParentRouteElement','ChildRouteElement']

and should have one childrouteElement asDefault also.

In main Route config you should have:

@RouteConfig([
  { name: "Videos", component: ChildrenCmp, path: "/videos/..."}
])

Than in child Component:

@RouteConfig([
  { name: "ChildCmp" component: ChildCmp, path: "/",
useAsDefault: true}])

Working example on Plunker

When you bootstrap your application, you may have referenced the ParentComponent as your router primary component instead of the ChildComponent .

You may need to have something like:

bootstrap(ParentComponent, [
  // ...
  provide(ROUTER_PRIMARY_COMPONENT, {useValue: ChildComponent})
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM