【问题标题】:Why does Angular 2 render app component template twice为什么 Angular 2 渲染应用程序组件模板两次
【发布时间】:2018-02-21 08:46:58
【问题描述】:

我想在整个应用程序中显示通用页眉和页脚。但是当我尝试这样做时,它会显示两次:-

app.component.html

<header>
    Header
</header>
<router-outlet></router-outlet>
<footer>
    Footer
</footer>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
}

app.module.ts

RouterModule.forRoot([
  {path: 'home', component: AppComponent},
  {path: '*', redirectTo: 'home', pathMatch: 'full'},
  {path: '**', redirectTo: 'home', pathMatch: 'full'}
])

结果

Header
Header
Footer
Footer

上次我通过创建页眉和页脚组件解决了这个问题。我知道如果我这样做会起作用,但我想了解为什么这是错误的......

【问题讨论】:

  • 页眉和页脚组件本身实际上是什么样的? (代码)
  • 我还没有创建页眉和页脚组件...上次我解决这个问题是通过创建页眉和页脚组件。但我不明白为什么这不起作用......

标签: angular angular-components router-outlet


【解决方案1】:

因为 App 组件是您的应用程序的根组件,它始终存在,并且也是在此根组件内由路由器出口显示的组件,用于“主”路径。所以你说路由器在应用组件内显示应用组件。

创建一个真实的、不同的家庭组件。不要为您的主页重用根组件。

【讨论】:

  • 解释得很好!谢谢!
  • 所以基本上,不要在你的路由模块中合并 app.component.ts,并将 home 的路由路径更改为空字符串''。
【解决方案2】:

在将 Angular 组件转换为 Web 组件的上下文中,以下发生在我身上(如果您或其他读者可以感觉到被这个特定用例所识别):

Angular 组件渲染两次的另一个原因是您可能正在将该组件注册为 web 组件(使用 @angular/elements 包),同时您使用的是同一个组件作为角分量。

例如,如果您在另一个 Angular 组件(例如 &lt;complex-title&gt;)中使用了一个 Angular 组件(例如 &lt;simple-title&gt;),并且您还将第一个组件注册为 Web 组件(例如 createCustomElement(&lt;simple-title&gt;)),那么第二个组件 (&lt;complex-title&gt;) 可以将组件的 angular 版本和 web 组件版本视为有效,然后渲染两次。

解决方案(在我的例子中)是创建另一个可以被两个组件重用的 Angular 组件(例如,&lt;simple-title&gt;&lt;complex-title&gt; 使用的 &lt;title-renderer&gt;)。

【讨论】:

    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2023-02-08
    • 2020-09-07
    • 2022-10-02
    • 2020-10-11
    相关资源
    最近更新 更多