Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
943 views
in Technique[技术] by (71.8m points)

angular - Changing router-outlet with *ngIf in app.component.html in angular2

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

{ path : "forgotPassword", component :ForgotPassword , outlet : "notlogedin" }

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 enable router-outletto overcome the problem it does not work. One router-outlet will get registered and no matter what you do, next router-outlet will not respond to the route changes.

So Here is The Solution

Using ngTemplateOutlet and ng-template we can provide a good solution to this problem by keeping only one router-outlet see below sample code.

<ul>
  <li><a routerLink="/login">login</a></li>
  <li><a routerLink="/dashboard">dashboard</a></li>
</ul>

<!--This is where my before login router stays-->
<div class="logedIn-route" *ngIf="routerActive">
<ng-container *ngTemplateOutlet="template"></ng-container>
</div>

<!--This is where my after login router stays-->
<div class="logedout-route" *ngIf="!routerActive">
  <ng-container *ngTemplateOutlet="template"></ng-container>
</div>


<ng-template #template>
  <router-outlet>
  </router-outlet>
</ng-template>

Try the fiddle

https://jsfiddle.net/imal/e4tyqv95/36/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...