我创建了一个主要组件,其中尝试渲染contentprojector组件,该组件定义了用于内容投影的ng-content区域。当我尝试使用ContentChild装饰器访问它时,它给出了undefined。
appComponent.ts的代码:
import { Component, ViewChild, AfterViewInit, ContentChild, AfterContentInit } from '@angular/core';
import { FirstChildComponent } from './first-child/first-child.component';
import { SecondChildComponent } from './second-child/second-child.component';
import { FirstContentComponent } from './first-content/first-content.component';
import { SecondContentComponent } from './second-content/second-content.component';
import { ContentProjectorComponent } from './content-projector/content-projector.component';
import { InsideProjectorComponent } from './inside-projector/inside-projector.component';
@Component({
selector: 'pm-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit, AfterContentInit {
@ViewChild(FirstChildComponent) fc : FirstChildComponent;
@ViewChild(SecondChildComponent) sF : SecondChildComponent;
@ViewChild(FirstContentComponent) fCC : FirstContentComponent;
@ViewChild(SecondContentComponent) sFC : SecondContentComponent;
@ContentChild(ContentProjectorComponent) cp: ContentProjectorComponent;
@ContentChild(InsideProjectorComponent) iP : InsideProjectorComponent;
ngAfterViewInit()
{
console.log(this.fc);
console.log(this.sF);
console.log(this.fCC);
console.log(this.sFC);
console.log(this.iP);
}
ngAfterContentInit()
{
console.log(this.cp);
}
}
App.component.html:
<section>
Inside of main app component
</section>
<pm-first-child></pm-first-child>
<pm-second-child>
</pm-second-child>
<pm-first-content></pm-first-content>
<pm-second-content></pm-second-content>
<pm-content-projector>
<section>
Inside app projector elememt yayyy
</section>
</pm-content-projector>
ContentProjector.html:
<ng-content>
</ng-content>
请帮忙为什么它没有给我内容投影仪组件的内容或对它的内容的引用。
答案 0 :(得分:1)
ContentProjectorComponent
不是ContentChild
,而是ViewChild
的{{1}}。因为它是作为直接子级放置在模板上的(而不是放在AppComponent
的开始和结束标记之间)
您可能对app-component
的定义感到困惑。在某个组件的ContentChild
和opening
标签内投射内容不会使该closing
component
。
相反,如果投影的ContentChild
包含其他一些content
组件,那么它将变成pm-projector-child
组件的ContentChild
(如下例所示)。
请参见here,以了解pm-content-projector
和ViewChild
之间的区别
Ex:
app.component
ContentChild
小demo