1
我遇到了一個問題,我沒有找到失敗。 我試圖在Angular中使用ContentChild。 我創建了2個組件(BlogEntries, BlogEntry)
一個知道這些並將該模塊導入到主要組件app.component的模塊。Angular ContentChild
BlogEntries
使用BlogEntry
作爲ChildContent。在BlogEntries模板中,我設置了<ng-content></ng-content>
元素。
當即時啓動應用程序。 顯示來自BlogEntries的資料,但不包含來自Contentchild BlogEntry的資料。
希望有人能幫助我。
的AppModule: -
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BlogentriesModule } from './blogentries/blogentries.module';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BlogentriesModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
AppComponent模板
<wr-blog-blogentries></wr-blog-blogentries>
BlogEntries模塊
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogentriesComponent } from './blogentries.component';
import { BlogentryComponent } from './blogentry/blogentry.component';
@NgModule({
imports: [
CommonModule
],
declarations: [BlogentriesComponent, BlogentryComponent],
exports: [BlogentriesComponent]
})
export class BlogentriesModule {
}
BlogEntries元器件
import { Component, ContentChild, OnInit, AfterContentInit, QueryList } from '@angular/core';
import { BlogentryComponent } from './blogentry/blogentry.component';
@Component({
selector: 'wr-blog-blogentries',
templateUrl: './blogentries.component.html',
styleUrls: ['./blogentries.component.css']
})
export class BlogentriesComponent implements OnInit, AfterContentInit {
@ContentChild(BlogentryComponent) blogentry: BlogentryComponent;
constructor() { }
ngOnInit() {
}
ngAfterContentInit() {
console.log(`ngAfterContentInit - blogentry is ${this.blogentry}`);
}
}
個
BlogEntries模板
<p>
blogentries works!
</p>
<ng-content></ng-content>
BlogEntry組件
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'wr-blog-blogentry',
templateUrl: './blogentry.component.html',
styleUrls: ['./blogentry.component.css'],
})
export class BlogentryComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
BlogEntry模板
<div>
Blog Entry
</div>
Zöchbauer:我看過使用ContentChild的示例,其中沒有任何內容通過或者我錯了,像這樣:https://embed.plnkr.co/rSmStf53EZx4Dh4AlI1g/ – RonsonHD
''以我在回答' ' –
啊我們的代碼塊重新加載頁面後不可見我現在已經看到了。感謝您的幫助。 – RonsonHD