【发布时间】: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