异步 – 角2 |无法使用@ContentChildren获取子指令
发布时间:2020-12-17 17:08:06 所属栏目:安全 来源:网络整理
导读:我正在尝试从父指令获取嵌套指令,但@ContentChildren没有被填充.基本上我在图像上构建一个延迟加载,每个图像都是来自父指令的嵌套指令 例: parent.directive.ts: import ...@Directive({ 'selector': 'parentSelector'})export class ParentDirective impl
我正在尝试从父指令获取嵌套指令,但@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是默认值. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |