无法将子组件显示到父组件中

时间:2018-11-21 17:20:49

标签: angular

我有一个父级组件ViewCalendars

view-calendars.component.html

 <div class="container-calendar">
      <ca-month-header>
      </ca-month-header>
  </div>

view-calendars.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';  
import { ActivatedRoute } from '@angular/router';
import { MonthHeaderComponent } from './ca-month-header/month-header.component';

@Component({
  selector: 'ca-view-calendars',
  templateUrl: './view-calendars.component.html',
  styleUrls: ['./view-calendars.component.css']
})
export class ViewCalendarsComponent implements OnInit {
  @ViewChild(MonthHeaderComponent) header: any;
  ngOnInit() {
  }
}

和子组件MonthHeader

month-header.component.html

<div class="month-header">
  <div class="month">
    <label> Month </label>
  </div>
</div>

month-header.component.ts

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

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

  constructor() { }

  ngOnInit() {
  }

}

这就是我在DevTools中得到的。

enter image description here

我已经在模块中导入了组件,但我不明白为什么子组件未显示

我想念什么?

2 个答案:

答案 0 :(得分:1)

Angular编译器控制台上是否有任何错误?

如果没有,我建议您尝试在Month标头组件中打印不同的内容,例如h2标记中的内容,然后查看是否可以打印。您还应该确认组件是否在模块中正确声明和导入。

答案 1 :(得分:0)

我相信您的应用程序未编译月份组件。

这是您需要做的。 :

声明app.module.ts文件中的两个组件:

// in app.module.ts file 
import { MonthHeaderComponent } from './month-heder/month-heder.component';
import { ViewCalendarsComponent } from './view-calendars/view-calendars.component';

@NgModule({

  imports:      [ BrowserModule, FormsModule ],

  declarations: [ AppComponent, HelloComponent,MonthHeaderComponent,ViewCalendarsComponent ],

  bootstrap:    [ AppComponent ]

})

export class AppModule { }



then, where ever you want to use, use the components selectors to render them , like below  :
<!-- IN parent component.html file -->

<hello name="{{ name }}"></hello>
<p>
Parent child relation ships in angular  :  
</p>

<div class="container">
  <h1> This App component  parent </h1>
<div class="calendar-container">
  <!-- Declaring view calendars as child of App.component.ts -->
  <ca-view-calendars> </ca-view-calendars>
</div>
</div>

这是有效的stackblitz示例:

https://stackblitz.com/edit/angular-kfqdzn