3

問題:Angular2 @ContentChildren不填充內部父<ng-content>

@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() { } 

} 

enter image description here

回答

2

ContentChildren只會計算分配到current Component指令。根據你的情況,在ChildComponent指定test指令時,你應該在ChildComponent本身計算指令。

指這plunker我分叉你。

+0

此解決方案很好。我覺得角度應該能夠做到以上功能:( –

+0

@KevinUpton哦,我也覺得如此之前,但我仍然沒有找到任何東西后,一些研究。 – Pengyy