ContentChild无法与ngContent一起使用Angular

时间:2018-08-30 18:53:44

标签: angular

我创建了一个主要组件,其中尝试渲染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>

请帮忙为什么它没有给我内容投影仪组件的内容或对它的内容的引用。

1 个答案:

答案 0 :(得分:1)

ContentProjectorComponent不是ContentChild,而是ViewChild的{​​{1}}。因为它是作为直接子级放置在模板上的(而不是放在AppComponent的开始和结束标记之间)

您可能对app-component的定义感到困惑。在某个组件的ContentChildopening标签内投射内容不会使该closing component

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

请参见here,以了解pm-content-projectorViewChild之间的区别

Ex:

app.component

ContentChild

demo