使用angular2中的app.component.html中的*ngIf更改路由器插座

Opt*_*zal 13 angular2-template angular2-routing angular

我正在使用角度2.0决赛.我正在尝试更改主app.component.html中路由器插座的位置.模板正在更新精细显示,除了,我第一次使用router.navigate组件将不会显示在新的路由器插座中,并且没有错误.第二次和每次使用router.navigate后它都能正常工作.

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>
Run Code Online (Sandbox Code Playgroud)

ima*_*era 12

我想说请使用一个名称router-outlet哪个工作完全正常,但问题是这样的网址根本不是用户友好的,我个人认为带有插座名称的网址没有意义,

例如: -

路线

{ path : "forgotPassword", component :ForgotPassword , outlet : "notlogedin" }
Run Code Online (Sandbox Code Playgroud)

浏览器地址栏中的输出

HTTP://本地主机:4200 /(notlogedin:forgotPassword)

看看它在地址栏中看起来多么愚蠢.

因此,如果您尝试使用*ngIf有条件地禁用并启用router-outlet以克服该问题,则它不起作用.一个人router-outlet将被注册,无论你做什么,接下来router-outlet都不会回应路线变化.

所以这是解决方案

使用ngTemplateOutletng-template我们可以通过只保留一个router-outlet看下面的示例代码来提供一个很好的解决方案.

<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>
Run Code Online (Sandbox Code Playgroud)

试试小提琴

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

  • 在我不得不根据您是在台式机还是移动设备上移动插座的情况下非常有帮助。 (2认同)
  • 与异步身份验证防护相结合,这可能会导致调用 ngOnDestroy 而不调用 ngOnInit 的行为,就像我在这里描述的那样:/sf/answers/4087613141/ (2认同)

Edm*_*ake 7

您应该考虑使用命名router-outlet.

它在文档中说明:模板可能只包含一个未命名的模板.

<div *ngIf="authenticated() == false">
      <h1>not logged in</h1>
      <router-outlet name="notloggedin">
      </router-outlet>
    </div>
    <div *ngIf="authenticated()">
      <h1>logged in</h1>
      <router-outlet name="loggedin">
      </router-outlet>
    </div>
Run Code Online (Sandbox Code Playgroud)

路由器看起来像:

{ path: 'page1', component: Page1Component, outlet: 'notloggedin' },
{ path: 'page2', component: Page2Component, outlet: 'loggedin' }
Run Code Online (Sandbox Code Playgroud)

下面的例子在@yurzui 这个职位.