Search code examples
javascriptangularangular-routing

Angular - 2 components with same URL


I have a requirement where I need to use the same URL for 2 components.

Let's assume that the path is /path and the components are Foo and Bar.

Initially, I will see the Foo component and after pressing a link I will be redirected to the Bar component.

/path (Foo) => /path (Bar)

Now I see the Bar component and if I press the back button from the browser I need to be redirected to the Foo component

/path (Bar) =>back button=>/path (Foo)

And also if I press the "forward" button I need to see the Bar component

/path (Foo) =>forward button=> /path (Bar)

So, basically, I need to have the same URL but somehow keep all the features provided by the Angular router, just as if there were 2 different paths.

Is this possible? I've looked into the NavigationExtras options, like skipLocationChange, or replaceUrl but these options don't help me. Neither does history pushState or replaceState (or maybe I don't know how to make use of them).


Solution

  • It sounds like you'd be better off having one parent component with one url path, which contains the components foo and bar, and conditionally displays one or the other, depending on a query parameter in the URL. e.g.

    toggleFooBar(){
        this.showFoo = !this.showFoo;
        this.router.navigate([], 
            {
                relativeTo: this.activatedRoute,
                queryParams: {showFoo : this.showFoo}
            }
        );
    }
    

    More info about url params here.

    If you subscribe to changes in location in your parent component (and show / hide foo or bar accordingly), the forward and back buttons should work as required:

    ngOnInit() {
        this.location.subscribe(queryParams => {
            // Don't forget to unsubscribe on destroy
            this.showFoo = (this.activatedRoute.snapshot.queryParams.showFoo !== 'true')
        });
    }
    

    Live example with code here, but use this to see the forward / back buttons in action.

    I don't think you're going to be able to use the forward / back buttons without some change to the URL, because the URL has to change in order for there to be entries in the browser history to go back or forward through.

    It might be possible to get close with some serious code gymnastics... maybe you could use the query parameters and then take them off again? But even then, I think you'd be at risk of causing the browser / history to behave in unexpected ways, which will likely to more harm than good to your application.