【问题标题】:angular 2 | can't get child directives with @ContentChildren角 2 |无法使用 @ContentChildren 获取子指令
【发布时间】:2017-02-15 20:33:27
【问题描述】:

我正在尝试从父指令中获取嵌套指令,但 @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" 从服务异步加载

some-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>

问题在于“某些组件”循环,因为数据是异步加载的,@ContentChildren 为空。

注意:所有图像都显示在 some-component

有什么想法吗?提前致谢。

【问题讨论】:

    标签: asynchronous angular directive children


    【解决方案1】:

    有一个错误(在 2.0.1 中修复)@ContentChildren() 默认不搜索后代。您可以明确设置它

    @ContentChildren(ChildDirective, {descendants: true})
    

    在 2.0.1 中true 是默认值。

    【讨论】:

    • 此更改仅影响@ContentChild()@ContentChildren() 仍然需要将 descendants 设置为 true
    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2016-07-10
    相关资源
    最近更新 更多