首页 > 解决方案 > ContentChild 无法与 ngContent 一起使用 Angular

问题描述

我创建了一个主要组件,在其中尝试渲染 contentprojector 组件,该组件定义了用于投影内容的 ng-content 区域。当我尝试使用 ContentChild 装饰器访问它时,它给出了未定义的。

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>

您能否帮我解释一下为什么它没有给我内容投影仪组件的内容或对其内容的引用。

标签: angular

解决方案


ContentProjectorComponent不是ContentChild,而是ViewChildAppComponent。因为它是作为模板上的直接子级放置的(而不是放置在 的开始和结束标记之间app-component

您可能对 的定义感到困惑ContentChildopening在某些组件的and标记内投射内容closing不会做到这一点component ContentChild

相反,如果投影content包含一些其他pm-projector-child组件,那么它将成为ContentChild组件的pm-content-projector(如下面的示例所示)。

请参阅此处ViewChild以了解和之间的区别ContentChild

前任 :

应用程序组件

<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>  <!--- view child of app component -->
        <section>
            Inside app projector elememt yayyy
        </section>
        <pm-projector-child>  --> content child of ContentProjectorComponent
        </pm-projector-child>
</pm-content-projector>

演示


推荐阅读