在 Angular 中嵌入组件 2

Embed component in Angular 2

我尝试了几种不同的方法,但我能找到的所有示例都使用模板而不是 templateUrl 来嵌入组件。

我的核心是一个 header 组件,我想将其分开,因为它具有登录功能,并根据您是否登录显示不同的信息。我认为与其将其放入应用程序组件,不如将其分解为自己的组件。本质上,现在发生的事情是构建查找,但不会超过 Loading...

即使它没有出错,我假设它不知道如何处理 <header-component></header-component

我为此尝试了几个不同的语法选项,但结果都是一样的。我觉得我缺少的是以某种方式传递导入的组件。我只是不确定如何。

app.component.ts

import { Component } from '@angular/core';
import { Router } from "@angular/router";

import { HeaderComponent } from './header/Header.Component';

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

}

app.component.html

<div id="header">Header</div> /*temporary place holder */
<header-component></header-component>
<router-outlet></router-outlet>

header.component.html(当前未完成。完成后将保留登录功能)

<ul id="links">
    <li>
        <a href="/">Home</a>
    </li>
    <li>
        <a href="/census">Census</a>
    </li>
</ul>

header.component.ts

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


@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {


  constructor() { }

  ngOnInit() {
  }



}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { routing } from "./app.routing";

import { AppComponent } from './app.component';
import { EncounterComponent } from './encounter/encounter.component';
import { CensusComponent } from './census/census.component';
import { PracticeComponent } from './practice/practice.component';
import { LocationComponent } from './location/location.component';
import { CensusManagementComponent } from './census-management/census-management.component';
import { LoginComponent } from './login/login.component';
import { UserComponent } from './user/user.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './header/header.component';

@NgModule({
  declarations: [
    AppComponent,
    EncounterComponent,
    CensusComponent,
    PracticeComponent,
    LocationComponent,
    CensusManagementComponent,
    LoginComponent,
    UserComponent,
    HomeComponent,
    HeaderComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

您的 header 组件选择器是 app-header 但您在 HTML.

中将其用作 <header-componet></header-component>

HTML 标签名称应始终与 selector 名称相同。在您的 app.component.html 中,更改为

<div id="header">Header</div> /*temporary place holder */
<app-header></app-header>