10

In angularJS ui-router allows us to use 2 components with the same route using states (like in this example Angular UI Router: Different states with same URL?).

Is it possible to achieve the same behaviour in angular2? If it is could you link/provide some examples or workarounds?

The use case here would be something similar to Facebook or Twitter where the URL stays the same but the content changes depending on if you are logged in or not.

So far the only way I can think off to achieve this is using *ngIf in the 'parent' template to select selector of one of the two 'children' components. Something like this:

<home-logged-in *ngIf="authenticated()"></home-logged-in>
<home-logged-out *ngIf="!authenticated()"></home-logged-out>

Are there any recommended ways to do this?

Thanks

Community
  • 1
  • 1
dem00n
  • 101
  • 1
  • 6

1 Answers1

0

You can have routes with parameters like

/article/:id/detail

Where /article/123/detail and /article/abc/detail lead to the same component.

See for example this tutorial https://angular.io/docs/ts/latest/tutorial/toh-pt5.html (Search for "Configure a Route with a Parameter")

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Thanks for the answer, however this is not what I am looking for. What I need is 1 route leading to 2 components conditionally. Like in this pseudo-code: request '/home'; if (authenticated == true): go to 'authenticated_home' component else go to 'public_home' components – dem00n May 05 '16 at 09:32
  • I see. I'm pretty sure the router itself doesn't provide any support for this. I guess `*ngIf`is a good workaround. What about using different routes and automatically redirect to the other variant if a route is passed for a logged in user but the user is not logged in (or vice versa) like explained here http://www.captaincodeman.com/2016/03/31/angular2-route-security/ – Günter Zöchbauer May 05 '16 at 09:39
  • 1
    I have considered that, however this will change the URL in the browser which I am trying to avoid. For now I will go with *ngIf and see if anyone else proposes alternative solution. – dem00n May 05 '16 at 09:46
  • You could build a similar approach with a custom router-outlet like in the linked blog, but instead of redirecting just adding a different component. You would just need some global replacement components - When `ComponentA` is configured in the current route and the user is already logged in insert `ComponentALoggedIn` instead. This way you get an universal solution. – Günter Zöchbauer May 05 '16 at 09:52
  • 1
    Thanks. Actually that is much cleaner than depending on conditionals in html. – dem00n May 05 '16 at 10:01