在angular2的app.component.html中使用* ngIf更改路由器出口 [英] Changing router-outlet with *ngIf in app.component.html in angular2
问题描述
我正在使用angular 2.0 final.我正在尝试在主app.component.html中更改路由器出口的位置.模板正在更新精细显示,除非是我第一次使用router.navigate,该组件不会显示在新的router-out中,并且没有错误.在我使用router.navigate之后的第二次和每次都可以正常工作.
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.
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>
推荐答案
我想说的是,请使用命名为router-outlet
的文件,该文件可以很好地工作,但对我而言,问题在于此类网址根本对用户不友好,并且我个人认为带有出口名称的网址没有任何意义,
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,
例如:-
路线
{ path : "forgotPassword", component :ForgotPassword , outlet : "notlogedin" }
浏览器地址栏中的输出
http://localhost:4200/(notlogedin:forgotPassword)
查看它在地址栏中的外观多么愚蠢.
see how stupid that it looks in the addressbar.
因此,如果您尝试使用*ngIf
有条件地禁用和启用router-outlet
以克服该问题,则它将不起作用.一个router-outlet
将被注册,无论您做什么,下一个router-outlet
都不会响应路线更改.
so if you try to use *ngIf
to conditionally disable and enable router-outlet
to 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.
这就是解决方案
使用ngTemplateOutlet
和ng-template
,我们可以通过仅保留一个router-outlet
来解决此问题,请参见下面的示例代码.
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>
尝试小提琴
https://jsfiddle.net/imal/e4tyqv95/36/
这篇关于在angular2的app.component.html中使用* ngIf更改路由器出口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!