角2 |无法通过@ContentChildren获取子指令

时间:2016-10-06 23:26:43

标签: asynchronous angular directive children

我试图从父指令获取嵌套指令,但未填充@ContentChildren。基本上我是在图像上构建一个延迟加载,每个图像都是来自父指令的嵌套指令

示例:

parent.directive.ts

import ...

@Directive({
    'selector': 'parentSelector'
})
export class ParentDirective implements onInit, AfterContentInit {
    @ContentChildren(ChildDirective) private items: QueryList<ChildDirective>;

    ngOnInit(): void {}

    ngAfterContentInit(): void {
        console.log(this.items, this.items.toArray()); // <---

        // call a child directive method...
        this.items.forEach((item: ChildDirective) => {
            item.makeSomething();
        });
    }
}

此处,this.items未填充

child.directive.ts

import ...

@Directive({
    selector: 'childSelector'
})
export class ChildDirective {
    makeSomething(): void {
        console.log('called from ParentDirective');
    }
}

app.component.ts

import ...

@Component({
    selector: 'app',
    template: `<div>
        <some-component parentSelector [items]="itemsData"></some-component>
    </div>`
})
export class AppComponent {
    // NOTE: "itemsData" is loaded asynchronously from a service
    ...
}

属性&#34; itemsData&#34; 是从服务异步加载的

一些-component.component.html

<!-- 'items' was obtained from AppComponent @Input('items')
     see also: 'itemsData' on AppComponent
-->

<div *ngFor="let image of images">
    <img childSelector src="image.src">
</div>

问题在于某个组件&#39;循环,因为数据是异步加载的,@ ContentChildren是空的。

注意:所有图像都显示在某个组件

任何想法?提前谢谢。

1 个答案:

答案 0 :(得分:1)

有一个错误(在2.0.1中已修复),@ContentChildren()默认情况下不会搜索后代。您可以通过明确设置来解决这个问题

@ContentChildren(ChildDirective, {descendants: true})

在2.0.1 true中是默认值。