路由器元素显示两次

时间:2021-01-20 13:22:25

标签: angular

在我感到困惑之后,我尝试编写一个简单的路由练习。当我使用我的代码实现我的代码时,即使我的路由器元素中没有按钮,我也会看到有 2 个按钮。但是当我在没有路由器插座的情况下实施时,我会在屏幕上看到正确的 1 个按钮。

这是我的样本;

app.component.html:

<div>
  <button type="button" class="btn btn-outline-secondary"><a
      routerLink="./elements"
      routerLinkActive="active">Table</a></button>
</div>

<router-outlet></router-outlet>

app.routing-mdule.ts:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { Element2Component } from './element2/element2.component';
const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    children: [
      { path: 'elements', component: Element2Component },
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

element2.component.html:

<p>element2 works!</p>

作为更深入的解释;当我在 app.component.html 上尝试这个时:

<div>
  <button type="button" class="btn btn-outline-secondary"><a
      routerLink="./elements"
      routerLinkActive="active">Table</a></button>
</div>

我看到一个按钮。同样,当我只应用路由器插座时,我只看到“元素有效!”正如预期的那样。但是当我尝试将这两个一起实现时,我看到 2 个按钮和“元素有效!”。为什么我只看到 1 个按钮和“元素有效!”在屏幕上?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的按钮显示两次,因为我认为 AppComponent 是您的根组件(并且始终存在),并且您也将其作为默认路径 ""。所以你的组件被加载了两次!

所以在这里,在你的默认路径中使用除 AppComponent 之外的另一个组件;不要重复使用它:)