【发布时间】:2018-11-28 08:32:54
【问题描述】:
为了访问组件中的指令,我尝试了Angular 2: Get reference to a directive used in a component,但这不适用于组件子组件中的指令。
子组件是使用 ViewContainerRef 动态创建的。
@ViewChildren(ViewRefDirective) allMyDirectives;
//This doesn't work for directives in the child components
我有多个不同的子组件,这就是为什么我不能在 ViewChild 中指定单个子组件的名称来访问其指令。
指令
@Directive({
selector: '[view-ref-host]',
})
export class ViewRefDirective {
constructor(public viewContainerRef: ViewContainerRef) {
}
}
父组件
<div>
<div view-ref-host>Parent block
<child-panel-one></child-panel-one>
<child-panel-two></child-panel-two>
<child-panel-three></child-panel-three>
</div>
</div>
子面板一组件
<div>
<div view-ref-host>Child panel one
<!-- html here -->
</div>
</div>
子面板二组件
<div>
<div view-ref-host>Child panel two
<!-- html here -->
</div>
</div>
子面板三组件
<div>
<div view-ref-host>Child panel three
<!-- html here -->
</div>
</div>
如何使用 ViewChild 装饰器访问父子组件中的所有指令?
【问题讨论】:
-
显示完整代码
-
父组件ts文件?
-
@fateme:我有 2000 行代码。不能分享。使用@ViewChildren(ViewRefDirective) allMyDirectives;在父组件中给我指令,但不包括子组件。
-
viewChildren 设置在
ngAfterViewInit可能你忘记了。 -
如果在视图渲染后不使用它,我的父组件指令也不会加载。你应该已经猜到了。并且在渲染所有子级之前,父级的渲染不会完成。
标签: angular decorator angular-directive