【发布时间】:2017-09-21 21:29:10
【问题描述】:
问题:
@ContentChildren 似乎不适用于父 <ng-content> 容器。
即使内容是组件的子组件。
Plunker:https://plnkr.co/edit/J5itJmDfwKwtBsG6IveP?p=preview
注意:我使用的是{descendants: true}
示例代码:
主 HTML:
<div>
<child>
<test></test>
<test></test>
<test></test>
</child>
<br><br>
<parent>
<test></test>
<test></test>
<test></test>
</parent>
</div>
子组件:
<h2>Child</h2>
<parent>
<ng-content></ng-content>
</parent>
父组件:
<h3>Parent</h3>
<ng-content></ng-content>
<div class='length'>Line count : {{length}}</div>
问题
test组件的长度对于子组件是0,对于父组件是3。
详细代码:
import {
Component, ContentChildren, Directive
} from '@angular/core';
@Directive({selector: 'test'})
export class Test {}
@Component({
selector: 'parent',
template: `
<h3>Parent</h3>
<ng-content></ng-content>
<div class='length'>Line count : {{length}}</div>
`
})
export class ParentComponent {
@ContentChildren(Test, {descendants: true}) private tests : QueryList<Test>;
constructor() { }
get length () {
return this.tests.length;
}
}
import {
Component
} from '@angular/core';
@Component({
selector: 'child',
template: `
<h2>Child</h2>
<parent>
<ng-content></ng-content>
</parent>
`
})
export class ChildComponent {
constructor() { }
}
【问题讨论】:
-
为什么要颠倒父子?孩子应该在父母内部,反之亦然。无论如何,这是我遇到的确切问题。并且文档没有说它不应该工作。 angular.io/api/core/ContentChildren :/
标签: javascript angular angular2-components angular2-ngcontent