【问题标题】:Angular 2+: Get child element of @ViewChild()Angular 2+:获取@ViewChild() 的子元素
【发布时间】:2019-01-20 13:04:53
【问题描述】:

如何在没有明确声明的情况下访问 Angular 2+ 中 @ViewChild() 的子元素(此处为:<img>)?

在template.html中

<div #parent>
  <!-- There can be anything than <img> -->
  <img src="http://localhost/123.jpg" alt="">
</div>

在component.ts中

@ViewChild('parent') parent;

public getFirstChild() {
   this.firstChild = this.parent.? //
}

目标是能够创建一个通用组件,该组件使用:

<div #parent>
    <ng-content></ng-content>
</div>

因此#parent 的子元素需要无需显式声明即可访问。

【问题讨论】:

    标签: angular typescript angular-components viewchild


    【解决方案1】:

    可以使用ViewChild给出的ElementRefnativeElement属性来获取对应的HTML元素。从那里,标准 DOM 方法和属性可以访问其子项:

    • element.children
    • element.querySelector
    • element.querySelectorAll

    例如:

    @ViewChild("parent") private parentRef: ElementRef<HTMLElement>;
    
    public getChildren() {
      const parentElement = this.parentRef.nativeElement;
      const firstChild = parentElement.children[0];
      const firstImage = parentElement.querySelector("img");
      ...
    }
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

    • 太好了,谢谢!是否有额外的 Angular 方式来访问子元素?
    • “Angular 方式”将使用模板引用变量,但我不知道它们是否可以用于嵌入的内容。
    • 太棒了!这是我发现的唯一让我选择注入到 ng-container 中的未知类型的动态生成组件,其中 *ngComponentOutlet 在我的父组件中。
    【解决方案2】:

    使用ViewChildren 代替它获取具有相同标签的所有元素。

    @ViewChildren('parent') parents: QueryList<any>;
    

    将这些元素转换为数组:

    const arr = this.parent.toArray();
    

    选择第一个元素:

    const el = arr[0]
    

    访问第一个元素的子 html: const innerHtml = el.nativeElement.innerHtml;

    【讨论】:

    • 但这不会访问 ,是吗?我需要访问#parentchild
    • 为什么不直接访问 img 而不是通过 parent。如果你有充分的理由,那么你可以使用 innerHtml 来访问孩子。 const el = arr[0].nativeElement.innerHtml
    • 正如我所提到的,父级具有动态内容。所以我不想有一个明确的内容访问器。
    【解决方案3】:

    在您的情况下,当您只需要一个和第一个孩子时。

    this.parent.nativeElement.firstChild

    【讨论】:

      【解决方案4】:

      HTML

      <div #parent>
        <span id="child">
      </div>
      

      TS

       @ViewChild('parent',{static:false}) parentDiv:ElementRef
       this.parentDiv.nativeElement.firstChild
      

      如果你想在其中做任何操作,你可以检查一下renderer2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-11
        • 2018-01-24
        • 2018-10-04
        • 2016-06-21
        • 2018-01-17
        • 2018-08-14
        • 2018-02-21
        • 1970-01-01
        相关资源
        最近更新 更多