Angular 4 Component呈现为空

时间:2017-11-15 06:12:43

标签: html angular

我是Angular的新手,我正在尝试定义一个组件并在我的主页面中使用它。

问题是当我在index.html中使用组件时,我只能看到<custom-component></custom-component>为空,其中没有任何内容。

所以我做的是:

  • 在Angular cli中:ng生成组件自定义。

  • custom.component.html中的
  • 我在段落标记中只有一个文本。

  • index.html中的
  • 我将custom.component.ts(app-custom)中的选择器作为标记插入。

  • app.module.ts中的
  • 我导入了自定义组件。
  • ng serve仅输出app-custom标签,但不包含应该在其中的段落标记。

我错过了什么?

更新 我的组件代码:

custom.component.html

<p>
 component works!
</p>

custom.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-custom',
  templateUrl: './custom.component.html',
  styleUrls: ['./custom.component.css']
})
export class CustomComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

的index.html

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>TestApp</title>
  <base href="/">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> 
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-custom></app-custom>
</body>
</html>

app.module.ts:

import { CustomComponent } from './custom/custom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http'; 
import { FlexLayoutModule } from '@angular/flex-layout';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
     BrowserAnimationsModule,
    FlexLayoutModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3 个答案:

答案 0 :(得分:2)

尝试在声明=&gt;之后添加导出[AppComponent,CustomComponent]?在app.module中。或者使用最新版本

创建一个新的cli项目

答案 1 :(得分:1)

在NgModule.bootstrap中,添加您自己的组件。

@NgModule({
  declarations: [
    AppComponent,
    CustomComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [
    AppComponent, 
    CustomComponent
  ]
})
export class AppModule { }

答案 2 :(得分:0)

在index.html中尝试添加Appcomponent选择器标签,在Appcomponent模板中引用自定义组件选择器,不要忘记在app模块中导入和声明自定义组件并引导App组件,以便呈现app组件在内部引用您的自定义组件的负载。如果您使用的是AngularCli,那么只需从单个组件开始就有很多教程,一切都很容易。

相关问题