如何在Angular2中查找DOM元素的子元素和父元素

Emi*_*cci 22 angular

我知道我可以获取组件的DOM元素

constructor(el: ElementRef){}
Run Code Online (Sandbox Code Playgroud)

但是我如何访问它的孩子(例如通过按类或id搜索)和主持人?

el.nativeElement.children
el.nativeElement.parent
el.nativeElement.host
Run Code Online (Sandbox Code Playgroud)

一切都行不通.

我一直在寻找答案,没有运气.非常感谢您的帮助.

编辑感谢yurzui的评论,我意识到el.nativeElement.children组件视图初始化后的工作.但是我仍然无法访问主机元素.

另外,正如JB Nizet指出的那样,在Angular2中操作DOM元素是不公平的.但是,我在组件类中需要的DOM元素的唯一内容是元素的宽度.如果我知道如何将此值绑定到类属性,我将在不访问DOM的情况下解决该问题.我之前尝试过类似的东西

<div [width] = "style.width"></div>
Run Code Online (Sandbox Code Playgroud)

(width我的组件的类的属性,其视图包含上面的div)但我不能让它工作.

yur*_*zui 40

尝试在ngAfterViewInit事件中使用您的代码.

而且您需要使用parentNode属性而不是parent

export class App {
  el: ElementRef;
  constructor(el: ElementRef){
    this.el = el; 
  },
  ngAfterViewInit() {
    const hostElem = this.el.nativeElement;
    console.log(hostElem.children);
    console.log(hostElem.parentNode);
  }
}
Run Code Online (Sandbox Code Playgroud)

https://plnkr.co/edit/iTmsNaIoU9NNUEFRe4kG?p=preview


san*_*oid 8

孩子们:

el.nativeElement.querySelector('.some-child-class-name');
Run Code Online (Sandbox Code Playgroud)

父母:

el.nativeElement.closest('.some-parent-class-name')
Run Code Online (Sandbox Code Playgroud)


Uli*_*lko 6

由于this.el.nativeElement.children返回子节点数组,因此您可以简单地执行this.el.nativeElement.children [0]。

import { Component, AfterViewInit,  ElementRef } from '@angular/core'; 

export class MyComponent implements ngAfterViewInit {
  el: ElementRef;

  constructor(el: ElementRef){
    this.el = el; 
  }

  ngAfterViewInit() {
     console.log(this.el.nativeElement.children[0]);
     console.log(this.el.nativeElement.children[0].offsetHeight);
  }
}
Run Code Online (Sandbox Code Playgroud)