首页 > 解决方案 > 为什么我的标题没有在这个简单的 Angular 应用程序中呈现?

问题描述

我是 Angular 的新手,我正在创建一个简单的应用程序来动手学习。我开始使用shared.module.ts我的标题并将其导入我app.module.ts的,但是当我运行应用程序时,我不到我的<app-header></app-header>渲染。下面是我的代码,有人能告诉我什么是错的吗?我相信我正在以正确的方式导出/导入/声明事物。

shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HeaderComponent } from './components/header/header.component';



@NgModule({
  declarations: [HeaderComponent],
  imports: [
    CommonModule
  ],
  exports: [
    HeaderComponent // exporting header component from shared module here
  ]
})
export class SharedModule { }

app.module.ts

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

//application modules
import { AppRoutingModule } from './app-routing.module';
import {BlogModule} from './blog/blog.module';
import { SharedModule} from './shared/shared.module'

//components
import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';

@NgModule({
  declarations: [
    AppComponent,
    DashboardComponent//declaring the dashboard component
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BlogModule,
    SharedModule //importing the shared module here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

仪表板.component.html

Hello, Header is below
<app-header></app-header>

我在浏览器上看到的:

在此处输入图像描述

您可以看到标头没有加载,并且控制台中也没有错误。

标签: angulartypescriptangular-module

解决方案


您已经在 App 模块中声明了 Dashboard 组件,并在此处导入 Shared 模块。但是您在 Dashboard 组件中使用 Header 组件,而不是 App 组件。它行不通。您应该为 Dashboard 组件使用单独的模块并在那里导入 Shared 模块以在其中使用 Header 组件。或者只是在 app.component.html 中使用 Header 组件。


推荐阅读