Angular routerLink正在追加替换的路由插座

时间:2017-12-30 22:16:13

标签: angular typescript angular-router routerlink

我正在学习Angular和TypeScript。现在我正在开发一个仅用于学习目的的简单应用程序。我遇到了routeLink的问题。我的一个routeLink是将新HTML添加到现有的HTML而不是替换它。我有复杂的组件树视图和结构。请参阅下面的方案。

这是我的主要app-routing.module

const routes: Routes = [
    { path: '', loadChildren: './layout/layout.module#LayoutModule', canActivate: [AuthGuard] }
];

我的app.component.html

<router-outlet></router-outlet>

所以我将拥有独立的LayoutModule及其路由配置。

const routes: Routes = [
    {
        path: '',
        component: LayoutComponent,
        children: [
             { path: 'outcome', loadChildren: './outcome/outcome.module#OutcomeModule' }
        ]
    }
];

我的layout.component

的html
<app-header></app-header>
<app-sidebar></app-sidebar>
<section class="main-container">
    <router-outlet></router-outlet>
</section>

再次,我将有结果模块及其路由配置。

这是我的结果 - routing.module配置

 {
    path: '',
        component: OutcomeComponent,
        children: [
            { path: '', redirectTo: 'list' },
            { path: 'list', component: ListOutcomeComponent },
            { path: 'add', component: CreateOutcomeComponent }
        ]
  },

这是我的结果.component.html

<div [@routerTransition]>
  <h2 class="text-muted">Page Title
    <small>This is small title</small>
  </h2>
  <router-outlet></router-outlet>
</div>

所以根据我的代码,如果我访问“结果/添加”和“结果/列表”,它将使用相应的组件。我的路线配置在此阶段仍然完美运行。当我访问“结果/添加”网址时,outcome.component.html中的路由出口将替换为“结果/列表”的CreateOutcomeComponent和ListOutcomeComponent。问题始于ListOutComponent。

这是我的create-outcome.component.html

<div>
    <h1>Add/create new outcome</h1>
</div>

这是我的list-outcome.component.html

<div class="row">
<div class="col-md-12">
<a class="btn btn-primary" [routerLink]="['/outcome','add']">Add new outcome <i class="fa fa-plus"></i></a>
</div>
</div>

如您所见,我在list-outcome.component.html中创建了一个导航到“结果/添加”的链接(routerLink)。因此,如果我点击该链接,则当前现有的整个内容应该替换为CreateOutcomeComponent的HTML内容,包括链接(锚点)本身。但是,当我点击链接时,内容不会被替换,而是将其附加或添加到现有内容中。请参阅下面的屏幕截图,以便更好地理解。

这是我看到的,当我访问“结果/列表”时:

enter image description here

如果我点击按钮,它应该被CreateOutcomeComponent中的内容替换。但是当我这样做时,就发生了这种情况。

enter image description here

正如您在屏幕截图中看到的,内容已添加到现有内容的顶部。但它应该被替换。为什么?我该如何解决这个问题?

但是,当我直接从进入浏览器的URL访问“结果/添加”时,它正如预期的那样工作。

enter image description here

0 个答案:

没有答案