我正在尝试在我的 angular 应用程序中实现一些功能。我创建了一个父指令appParent和另外两个指令appChildAbc和appChildXyz.
我想要做的是,每当我appParent在元素上应用指令时,我想检查它的子元素(同一组件中的原生 HTML 元素)并将一些逻辑应用于这些子元素。
经过多次搜索和努力,我找到了一种使用ViewContainerRefinParentDirective和@ViewChildrenin 的方法AppComponent,但我不得不使用((this.viewContainerRef as any)._view.nodes),这看起来不像是正确的方法。
有没有其他方法可以获得Child Elements父指令中的引用??
示例堆栈闪电战 在这里
随意分叉代码并根据需要进行更新。提前致谢
export class ParentDirective {
constructor(private vcr: ViewContainerRef) {}
ngAfterViewInit() {
console.log((this.vcr as any)._view.nodes);
let lists = (this.vcr as any)._view.nodes.filter(
x => x.constructor.name === "QueryList"
);
lists.forEach(list => {
list.toArray().forEach(x => {
if (x.constructor.name === "ChildXyzDirective")
x.elementRef.nativeElement.style.background = "red";
else x.elementRef.nativeElement.style.background = "green";
console.log(x);
}); …Run Code Online (Sandbox Code Playgroud)