【问题标题】:Separating the header/footer from content with Angular 4使用 Angular 4 将页眉/页脚与内容分开
【发布时间】:2018-06-21 13:05:06
【问题描述】:

我已经开始学习使用 Angular,到目前为止,它看起来相当简单。我选择转换我现有的网站主题之一以熟悉该过程,但遇到了有关正确使用的问题。

到目前为止,我的理解是每个页面都是一个组件。我在 app.component.html 中有我的索引内容,然后每个子页面也是一个单独的组件。但是,我想将header/footer HTML 分开,并像过去在 PHP 中那样包含它。

我的问题是,header/footer 应该是单个组件还是应该只是单个 HTML 文件,包括使用 ng-include?我意识到两者都可以,但不知道哪个是 Angular 开发人员的传统实现。

我正在尝试以下方法,但页眉/页脚组件似乎没有加载。它们在 app.component.html 中运行良好,但在 index.html 中运行良好。

index.html

<body>
  <app-header></app-header>
  <app-root></app-root>
  <app-footer></app-footer>
</body>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';


import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { ProductComponent } from './product/product.component';
import { ProductsComponent } from './products/products.component';


@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    FooterComponent,
    ProductComponent,
    ProductsComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

【问题讨论】:

    标签: javascript php html css angular


    【解决方案1】:

    您应该创建页眉和页脚组件并在AppComponent 中使用它。

    如果您想使用 i18n 工具(如 translate),或者如果您想在用户登录时更改页眉或页脚,这将很有帮助。

    应用结构应该是这样的。

    AppComponent
    |
    |----> HeaderComponent
    |----> Router-Outlet ---> Page content should be in the container.
    |----> FooterComponent
    

    这就是你需要的文件。您不能将 index.html 中的组件作为应用程序的角度引导程序而不是其他组件。

    【讨论】:

    • 不,将它们创建为组件并像&lt;appHeader&gt;&lt;appFooter&gt; 一样包含它们,不要使用ng-include
    • 我更新了原始帖子以显示我现在拥有的代码,但它不加载页眉/页脚,只加载应用程序根。知道为什么吗?如果我将 添加到 app.component.html 它可以工作,但在添加到 index.html 时不起作用,如上所示。
    • 你有那些组件?你在 appModule 中导入了吗?
    • 我确实有这些组件(它们在从 app.component.html 链接时起作用,而不是 index.html)并且它们被自动添加到 app.module.ts,导入和声明就在那里。
    • AppComponent的模板中添加appHeaderappFooter。不在 index.html 中
    猜你喜欢
    • 2016-10-31
    • 2019-11-20
    • 2013-03-16
    • 2023-03-17
    • 2017-11-06
    • 2022-01-15
    • 1970-01-01
    • 2012-09-24
    • 2019-10-02
    相关资源
    最近更新 更多