加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角 – @ContentChildren未被填充

发布时间:2020-12-17 09:17:41 所属栏目:安全 来源:网络整理
导读:我有三个组件:应用程序,父母和孩子: 应用程序组件 @Component({ selector: 'app',directives: [Parent,Child],template: 'parentchildhi/childchildthere/child/parent'})export class AppComponent { constructor() { }} 父组件 @Component({ selector: '
我有三个组件:应用程序,父母和孩子:

应用程序组件

@Component({
    selector: 'app',directives: [Parent,Child],template: '<parent><child>hi</child><child>there</child></parent>'
})
export class AppComponent {
    constructor() {
    }
}

父组件

@Component({
    selector: 'parent',template: '<div><h1>Parent</h1><ng-content></ng-content></div>'
})
export class Parent {
    @ContentChildren(Child) children: QueryList<Child>;
    ngAfterContentInit() {
        console.log(this.children);
    }
}

儿童组件

@Component({
    selector: 'child',template: '<div><h1>Child</h1></div>'
})
export class Child {
}

在Parent组件中可以看到,我尝试使用@ContentChildren获取子组件的列表,使用Child类型作为选择器.然而,这似乎不起作用 – 内容子列表始终未定义.

在ngAfterContentInit()方法中,我希望填充内容的孩子.

我错过了什么吗?

[更新]

因此,事实证明,当所有三个组件都在同一个文件中时,存在问题(请参阅控制台调试窗口,我输出内容的孩子):

Plnkr Demo of Issue

如果它们在单独的文件中,则问题消失:

Plnkr Demo Working

通常,我只将所有组件放在同一个文件中用于学习.但它让我很好奇有人知道为什么行为不同吗?

您需要使用 forwardRef引用尚未定义的类.见 this plunk.记住 ES6 classes are not hoisted.
@Component({
    selector: 'parent',template: '<div><h1>Parent</h1><ng-content></ng-content></div>'
})
export class Parent {
    @ContentChildren(forwardRef(() => Child)) children; // <!- HERE

    ngAfterContentInit() {
        console.log(this.children);
        console.log(this.children.length);
    }
}

UPD Mark Rajcok指出了一篇关于angle2中转发参考的优秀文章(见下文的注释).必读:thoughtram.io Forward references in Angular 2.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读