I am using angular 2.0 final. I am trying to change the location of the router-outlet in the main app.component.html. The template is updating fine display wise except, the first time I use router.navigate the component won't display in the new router-outlet, and there is no error. The second and every time after I use router.navigate it works properly.
example template of app.component.html
<div *ngIf="authenticated() == false">
<h1>not logged in</h1>
<router-outlet>
</router-outlet>
</div>
<div *ngIf="authenticated()">
<h1>logged in</h1>
<router-outlet>
</router-outlet>
</div>
I'd like to say please use a named
router-outlet
which work perfectly fine, but issue for me is that such urls are not user friendly at all and I personally believe url with outlet name does not make sense,ex:-
route
output in browser address bar
http://localhost:4200/(notlogedin:forgotPassword)
see how stupid that it looks in the addressbar.
so if you try to use
*ngIf
to conditionally disable and enablerouter-outlet
to overcome the problem it does not work. Onerouter-outlet
will get registered and no matter what you do, nextrouter-outlet
will not respond to the route changes.So Here is The Solution
Using
ngTemplateOutlet
andng-template
we can provide a good solution to this problem by keeping only onerouter-outlet
see below sample code.Try the fiddle
https://jsfiddle.net/imal/e4tyqv95/36/
I had to use
ViewContainerRef
so that both mobile and desktop would leverage the same router outlet:And I had no problem using
createEmbeddedView
for both:only thing is that you'll have to toggle this outlet if you switch between breakpoints. For example, from desktop to mobile resize:
You should consider using named
router-outlet
, instead.It states in the documentation: A template may hold exactly one unnamed .
The router will look like:
Here an example from @yurzui in this post.