Angular 2 add routerLink in child which points to root router
Solution 1
If you want to change the root route it should be
<a[routerLink]='["/NewItemForm"]'
Solution 2
RouterOutlet directive during component instantiation creates ChildRouter and injects it as "Router" to it. So components dynamically inserted to RouterOutlet have their own nested routers (with no RouteConfig on them). These routers are like tree leaves.
Thats why it complains that this router host component doesn't have routes configured.
All you have to do is to write it like this:
<a [routerLink]="['../NewItemForm']">
to get one step back in routers tree
(worked for me in Angular 2.0.0-beta.9)
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
Currently I am developing a web app using Angular 2 Beta 8. Now I am facing a problem with nested routes when using the routerLink directive.
The router hierarchy is:
AppCmp |-> NewItemFormCmp |-> UserDashboardCmp |-> MyItemsCmp
The involved components are:
@Component({ ... }) @RouteConfig([ {component: NewItemFormCmp, name: 'NewItemForm', path: '/item/new'}, {component: UserDashboardCmp, name: 'UserDashboardCmp', path: '/me/...', useAsDefault: true} ]) export class AppCmp { } @Component({ ... }) @RouteConfig([ {component: MyItemsCmp, name: 'MyItemsCmp', path: '/items', useAsDefault: true} ]) export class UserDashboardCmp { } @Component({ template: ` ... a([routerLink]='["NewItemForm"]' ... ` }) export class MyItemsCmp { }
The nested routing to the MyItemsCmp works perfectly fine. Now I would like to implement a button in the MyItemsCmp to navigate to the NewItemFormCmp by using the routerLink directive as shown in the component's template.
When the Component 'MyItemsCmp' is loaded, all elements of the template are rendered in the browser. But the link to the NewItemFormCmp is not working and there is an exception in the console.
Uncaught EXCEPTION: Component "MyItemsCmp" has no route config. in [["NewItemForm"] in MyItemsCmp@x:xxx]
When injecting the router in the constructor, I can navigate to the RootUser and navigate to the given route using "navigate".
How can I navigate from a 2nd level child component to a 1st level child using the RouterLink directive?
Thanks, Philipp
-
Admin about 8 yearsHi @micronyks, thank you for your answer and example. As shown in my question I tried this before. I try to avoid using router.navigate inside a click handler and prefer the routerLink directive on a HTML link element.
-
micronyks about 8 yearsGünter Zöchbauer's answer is perfect. but when I was playing with my plunker , answer was already posted. Never mind. enjoy ! this might help others :-)
-
sawe over 7 yearsfor angular 1.5, the same applies <a ng-link="['/NewItemForm']"