使用带有嵌套指令的 viewChildren 获取子项

Sac*_*pta 2 angular-directive viewchild angular

我正在尝试在我的 angular 应用程序中实现一些功能。我创建了一个父指令appParent和另外两个指令appChildAbcappChildXyz.

我想要做的是,每当我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)

App.component.ts

export class AppComponent  {
  name = 'Angular';
  @ViewChildren(ChildXyzDirective) xyzChildren: QueryList<ChildXyzDirective>;
  @ViewChildren(ChildAbcDirective) abcChildren: QueryList<ChildAbcDirective>;
}
Run Code Online (Sandbox Code Playgroud)

应用组件.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>
Run Code Online (Sandbox Code Playgroud)

mal*_*awi 5

您可以使用@ContentChildren装饰器来查询子指令

父指令

@Directive({
  selector: "[appParent]"
})
export class ParentDirective {

 @ContentChildren(ChildXyzDirective,{descendants: true}) 
 xyzChildren : QueryList<ChildXyzDirective>;

 @ContentChildren(ChildAbcDirective,{descendants: true}) 
 abcChildren : QueryList<ChildAbcDirective>;

  ngAfterContentInit() {  

      this.abcChildren.forEach(e => {
        e.elementRef.nativeElement.style.background = "red";
      });

      this.xyzChildren.forEach(e => {
        console.log(e)
        e.elementRef.nativeElement.style.background = "green";
      });

  }
}
Run Code Online (Sandbox Code Playgroud)

ContentChildren用于从内容 DOM 中获取元素或指令的 QueryList。每当添加、删除或移动子元素时,查询列表都会更新,查询列表的可观察更改将发出一个新值。

演示