i have two routes defined like this
children: [
{
path: 'Templates', component: TemplatesComponent
},
{
path: 'AddEditTemplate/:id', component: AddTemplatesComponent
}]
I have "cancel" button on AddTemplatesComponent view
<a class="btn btn-default no-margin" [routerLink]="['../Templates']">Cancel</a>
But clicking on cancel button it not navigate to "Templates" component and the url changed from "/AddEditTemplate/5" to "/AddEditTemplate/Templates". But url should change to "/Templates".
What am i doing wrong? please help.
In fact you have to go up 2 routes in the path. For example, let's suppose you're at root/AddEditTemplate/2
. If you go up 1 route in the path, you'll be at root/AddEditTemplate
. So, to be in root
again to get to root/Templates
, you should go up 2 routes in the path:
<a class="btn btn-default no-margin" [routerLink]="['../../Templates']">Cancel</a>
Checkout this Stackblitz demo => focus just in the files inside module-1
folder.
[UPDATE]: If you want to navigate programmatically, you can use the navigate
method of the Router
with 2 arguments: the same route as above and a config options containing the relativeTo
attribute specifying the current route as a starting point to calculate the relative paths. According to the docs: If no starting route is provided, the navigation is absolute.
constructor(
private _router: Router,
private _activatedRoute: ActivatedRoute
) {}
...
_navigate() {
this._router.navigate(['../../Templates'], {
relativeTo: this._activatedRoute
});
}