Search code examples
angulartypescriptangular-routing

Navigate back to parent URL


I'm trying to navigate back to parent URL when an option is changed and there are more route params and keep the current URL if there are no route params.

I will give you an example to make all more clear.

So, I have 3 components: CompA, CompB and CompC which holds a list of items and when I navigate to one of this I keep in URL:

/compA, /compB or /compC.

Navigate inside of each component to an item is possible and also kept in URL as /compA/item1.

I have a drop-down to select a specific client and what I want is to navigate back to parent when the client was changed and I have route params or to keep the specific route if don't.

For example, I'm on /compA/item2 and I change the client. The expected behaviour is to navigate to /compA. Or, If I'm on /compB and I change the client I should remain on /compB.

I found a solution using this

this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });

but doesn't work for me.


Solution

  • I found a solution using:

    const parentURL = this.router.url.split('/')[1];
    this.router.navigate([parentURL]);