【发布时间】:2020-04-10 18:13:17
【问题描述】:
我正在尝试在我的 Angular 应用程序中实现一些功能。我创建了一个父指令appParent 和另外两个指令appChildAbc 和appChildXyz。
我想要做的是,每当我在一个元素上应用appParent 指令时,我想检查它的子元素(同一组件中的本机 HTML 元素)并对这些子元素应用一些逻辑。
经过大量搜索和努力,我找到了一种方法来使用ParentDirective 中的ViewContainerRef 和AppComponent 中的@ViewChildren,但我不得不使用((this.viewContainerRef as any)._view.nodes),这看起来不正确方法。
有没有其他方法可以在父指令中获取Child Elements的引用??
stackblitz 示例here
请随意分叉代码并根据需要进行更新。提前致谢
父指令
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);
});
});
}
}
App.component.ts
export class AppComponent {
name = 'Angular';
@ViewChildren(ChildXyzDirective) xyzChildren: QueryList<ChildXyzDirective>;
@ViewChildren(ChildAbcDirective) abcChildren: QueryList<ChildAbcDirective>;
}
App.component.html
<div appParent>
Parent div directive
<div appChildAbc>
Abc Child directive 1
</div>
<div appChildAbc>
Abc Child directive 2
<div appChildXyz>
Xyz Child directive 1
</div>
<div appChildXyz>
Xyz Child directive 2
</div>
</div>
【问题讨论】:
标签: angular angular-directive viewchild