我有三个组件:App,Parent和Child:
应用组件
@Component({
selector: 'app',
directives: [Parent,Child],
template: '<parent><child>hi</child><child>there</child></parent>'
})
export class AppComponent {
constructor() {
}
}
Run Code Online (Sandbox Code Playgroud)
父组件
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
子组件
@Component({
selector: 'child',
template: '<div><h1>Child</h1></div>'
})
export class Child {
}
Run Code Online (Sandbox Code Playgroud)
正如您在Parent组件中看到的那样,我尝试使用类型作为选择器@ContentChildren来获取Child组件列表Child.但是,这似乎不起作用 - 内容子列表始终未定义.
在该ngAfterContentInit()方法中,我希望可以填充内容子项.
我错过了什么吗?
[更新]
事实证明,当所有三个组件都在同一个文件中时,问题就存在了(参见我输出内容子项的控制台调试窗口):
如果它们位于单独的文件中,则问题就会消失:
通常,我只会将所有组件放在同一个文件中以供学习.但它让我很好奇.有谁知道为什么行为不同?
ale*_*ods 22
您需要使用forwardRef 来引用尚未定义的类.看到这个插件.请记住,ES6课程并未悬挂.
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
UPD Mark Rajcok在angular2中指出了一篇关于前向参考的优秀文章(见下文评论).必读:aftertram.io Angular 2中的前向引用.
Kha*_*ela 10
您需要添加{ descendants: true }以包含嵌套的子项,
@Component({
selector: 'parent',
template: '<div><h1>Parent</h1><ng-content></ng-content></div>'
})
export class Parent {
@ContentChildren(Child, { descendants: true }) children: QueryList<Child>;
ngAfterContentInit() {
console.log(this.children);
console.log(this.children.length);
}
}
Run Code Online (Sandbox Code Playgroud)
后代- 真包括所有后代,否则只包括直系孩子。
| 归档时间: |
|
| 查看次数: |
9946 次 |
| 最近记录: |