Angular2路由器会附加组件,而不是替换它 [英] Angular2 router appends component instead of replacing it

查看:63
本文介绍了Angular2路由器会附加组件,而不是替换它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有路由器出口的Angular2应用程序,根据在侧面菜单中单击哪个链接,该出口显示不同的组件.

I have an Angular2 application with one router outlet that displays different components depending on which link is clicked in a side menu.

包含<router-outlet>的主要组件的标记看起来像这样

The markup for the main component containing the <router-outlet> looks like this

<div *ngIf="authenticated == false">
  <app-login></app-login>
</div>
<div *ngIf="authenticated">
  <div class="page home-page">
    <header class="header">
      <app-navbar></app-navbar>
    </header>
    <div class="page-content d-flex align-items-stretch">
      <div class="sidebar-container">
        <app-sidebar-menu></app-sidebar-menu>
      </div>
      <div class="content-inner">
      <app-page-header></app-page-header>
        <div id="sub-content">
          <router-outlet></router-outlet>
        </div>
        <app-footer></app-footer>
      </div>
    </div>
  </div>
</div>

如果单击 Demo 链接,则呈现演示组件,但是如果单击 Home 链接,则将home组件呈现在DOM中的演示组件上方. .多次单击它们将得到这样的DOM

If I click the Demo link, the demo component is rendered, but if I then click the Home link, the home component is rendered above the demo component in DOM. Clicking them a few times will result with a DOM like this

<div _ngcontent-c0="" id="sub-content">
    <router-outlet _ngcontent-c0=""></router-outlet>
  <app-home _nghost-c6="">...</app-home>
  <app-demo _nghost-c7="">...</app-demo>
  <app-home _nghost-c6="">...</app-home> <!-- Why so many here? Should be just either one <app-home> or <app-demo>  -->
  <app-demo _nghost-c7="">...</app-demo>
  <app-home _nghost-c6="">...</app-home>
  <app-demo _nghost-c7="">...</app-demo>
  <app-footer _ngcontent-c0="" _nghost-c5="">...</app-footer>
</div>

路线定义为

export const router: Routes = [
    { path: 'demo', component: DemoComponent, canActivate: [AuthGuard] },
    { path: 'home', component: HomeComponent, canActivate: [AuthGuard] }
]

<router-outlet>为什么不替换组件,而是在路由之间切换时添加了该组件的另一个实例"?

How come that the <router-outlet> doesn't replace the component, but instead adds another "instance" of the component when switching between the routes?

推荐答案

通过使用消除方法,我发现问题的根源是我的app.module.ts中的BrowserAnimations模块.通过从我的imports中删除它,问题解决了.我将研究创建一个Plunker来演示它.

By using the method of elimination, I found out that the culprit of the issue was the BrowserAnimations module in my app.module.ts. By removing it from my imports it the problem went away. I'll look into creating a Plunker to demonstrate it.

更新: 在 Github问题中对此进行了描述.

Update: This is described in this Github issue.

更新2017年12月13日: 现在,此PR已修复此问题,修复(动画):在发生CD故障时正确恢复并清理DOM. .

Update 2017-12-13: This has now been fixed with this PR, fix(animations): properly recover and cleanup DOM when CD failures occur.

这篇关于Angular2路由器会附加组件,而不是替换它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆