MrVoodoo
MrVoodoo

Reputation: 1083

Go to parent route in Angular 2

Let's say I have a component that creates or edits a thing.

The url for the creation is /things/create and the url for edition is /things/edit/4. These routes have the same parent.

Once I fill in the form, I call some webservice and then I go back to my previous state which was /things.

How do I tell angular to go back to the parent route?

I could use this.router.navigate(['../'], {relativeTo : this.route}); but ['../'] would only work for /things/create. For /things/edit/4 it would go back to /thing/edit which doesn't exist.

This component is used in two different places, one of which has an extra step before the creation so I can't use back().

Upvotes: 0

Views: 2628

Answers (4)

Hiren Gondhiya
Hiren Gondhiya

Reputation: 398

May be this idea a bit old school but I am sure it will work and is quite simplistic to implement. You can add query param called 'source' and navigate to 'source once the operation is done.

Upvotes: 0

Martin
Martin

Reputation: 16292

So you should be able to check for the id of the thing in the ActivatedRoute params to get the context if the component is creating or editing a component. If there is a param['thingId'] then go to ../../ otherwise go to ../

Upvotes: 0

Eddie Martinez
Eddie Martinez

Reputation: 13910

Logic based on the current url

if(router.url.indexOf('create')>= 0){
    this.router.navigate(['../'], {relativeTo : this.route});
 }else {
    this.router.navigate(['../../'], {relativeTo : this.route});
}

so if your current URL path contains the create you know you just have to go back one level, otherwise you go back two levels for the edit.

Use Input to get base URL

Another approach might be to have an @Input for the base URL to go back to. So each component that initializes your component has to pass it the parent url.

{
@Input
parentUrl;

this.router.navigate[parentUrl];
}

Upvotes: 3

Maks K
Maks K

Reputation: 3914

You can use

this.router.navigate['/things']

Upvotes: 0

Related Questions