【问题标题】:How to access parent HTML element from component?如何从组件访问父 HTML 元素?
【发布时间】:2016-07-22 09:19:48
【问题描述】:

就像问题一样 - 我有一个子组件,我想知道父元素的宽度是多少。我该怎么做?

【问题讨论】:

标签: angular


【解决方案1】:

注入元素本身:

constructor(private elRef: ElementRef){}

访问原生元素的父元素:

ngOnInit() {
  console.log(this.elRef.nativeElement.parentElement);
}

【讨论】:

  • 它会起作用,但直接访问本机元素不是一个好习惯。
  • @BenRichards。假设您有两个这样的组件:<parent><div><child></child></div></parent>。你将如何从ChildComponent 获取父级的 DOM 元素?我知道我可以通过简单地将其作为构造函数参数添加来轻松获取子组件中的“ParentComponent˙instance”,但我不知道如何获取实际元素?
  • 我已经尝试过了,但它没有检索到计算出的父 style
【解决方案2】:

您可以通过查找 this.elRef.closest 和一些匹配该父元素的选择器来访问最近的父 DOM 元素

constructor(private elRef: ElementRef){}

ngOnInit() {
   const parentElement = this.elRef.closest('.parent-element-class')
}

【讨论】:

  • Internet Explorer 不支持最近的,所以...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-26
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 1970-01-01
  • 2019-12-11
相关资源
最近更新 更多