异步 – 角2 |无法使用@ContentChildren获取子指令

前端之家收集整理的这篇文章主要介绍了异步 – 角2 |无法使用@ContentChildren获取子指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从父指令获取嵌套指令,但@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
    ...
}

属性“itemsData”是从服务异步加载的

一些-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>

问题出现在’some-component’循环中,因为数据是异步加载的,@ ContentChildren是空的.

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

有任何想法吗?提前致谢.

解决方法

有一个错误(在2.0.1中修复),默认情况下@ContentChildren()没有搜索后代.您可以明确地设置它

@ContentChildren(ChildDirective,{descendants: true})

在2.0.1中,true是默认值.

猜你在找的Angularjs相关文章