【问题标题】:Get children using viewChildren with nested directives使用带有嵌套指令的 viewChildren 获取孩子
【发布时间】:2020-04-10 18:13:17
【问题描述】:

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

我想要做的是,每当我在一个元素上应用appParent 指令时,我想检查它的子元素(同一组件中的本机 HTML 元素)并对这些子元素应用一些逻辑。

经过大量搜索和努力,我找到了一种方法来使用ParentDirective 中的ViewContainerRefAppComponent 中的@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


    【解决方案1】:

    你可以使用@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";
          });
    
      }
    }
    

    ContentChildren 用于从内容 DOM 中获取元素或指令的 QueryList。任何时候添加、删除或添加子元素 移动,查询列表将被更新,并且可以观察到的变化 查询列表将发出一个新值。

    demo ?

    【讨论】:

    • 太棒了!我曾尝试使用 @ContentChildren ,但缺少 {descendants: true} 。谢谢
    • 谢谢!!在尝试了一切之后,{descendants: true} 的诀窍就是!
    猜你喜欢
    • 2018-10-05
    • 2021-07-04
    • 2018-11-28
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 2016-07-05
    相关资源
    最近更新 更多