ISSUE:
@ContentChildren does not seem to work on Parent <ng-content>
containers.
Even if the content is a child of the component.
Plunker: https://plnkr.co/edit/J5itJmDfwKwtBsG6IveP?p=preview
NOTE: I Am using {descendants: true}
Example Code:
Main HTML:
<div>
<child>
<test></test>
<test></test>
<test></test>
</child>
<br><br>
<parent>
<test></test>
<test></test>
<test></test>
</parent>
</div>
Child Component:
<h2>Child</h2>
<parent>
<ng-content></ng-content>
</parent>
Parent Component:
<h3>Parent</h3>
<ng-content></ng-content>
<div class='length'>Line count : {{length}}</div>
Problem
The length of the test
component is 0 for the child component, but 3 for the parent component.
Detailed Code:
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() { }
}
ContentChildren
will count only directives assigned to the current Component
. For your situation, while assigning test
directive to ChildComponent
, you should count directives at ChildComponent
itself.
refer this plunker I forked from you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With