go back using routerLink

cucuru picture cucuru · Jul 11, 2018 · Viewed 24.8k times · Source

I'm using routerLink to go back in my page.

Current route can have 3 levels:

myurl.com/parent
myurl.com/parent/child
myurl.com/parent/child/grandchild

also, I have some differents components, so it won't be always parent, it can be parent1, or parent2, also for child and grandchild, for example:

myurl.com/parent2/child1/grandchild2

what I want is always go to the previous level, for example:

myurl.com/parent/child/grandchild -> myurl.com/parent/grandchild

what I did is:

<button [routerLink]="['../'']">
       back
</button>

but it always navigate to "myurl.com"

how can I solve it?

As some users suggested, I'm sharing my routing configuration:

in app.routing.ts:

const APP_ROUTES: Routes = [
{
  path: '',
  canActivate: [LoggedInGuard],
  children: [
    {path: '', redirectTo: '/mainPage', pathMatch: 'full'},
    {path: 'parent', loadChildren: 'app/parent/parend.module#ParentModule'
]},
{path: '**', redirectTo: ''}
];

in parent.routing.ts:

const PARENT_ROUTES: Routes = [
 {path: '', component: ParentComponent},
 {path: ':id', component: ChildComponent},
];

if in the browser I wrote:

myurl.com/parent -> it works

but clicking the back button fails

Answer

Vlad274 picture Vlad274 · Jul 11, 2018

If you're trying to navigate "up" one level, you're almost correct.

<a routerLink="..">Up</a>

This will navigate

myurl.com/parent/child/grandchild -> myurl.com/parent/child

However, if you want to truly navigate "back" like the browser's back button, you need to use javascript.

There are a variety of existing answers for that problem on this StackOverflow question


For anything more complicated, it will depend on exactly what you're trying to do - but it will likely require a click handler and some manual manipulation of the URL.