【问题标题】:Get list of all available <button> elements in component html获取组件 html 中所有可用 <button> 元素的列表
【发布时间】:2019-01-30 15:13:49
【问题描述】:

说我的组件很简单,比如:

<div>
  <button id="one" #one>one</button>
  <button id="two" #two>two</button>
  <button id="three" #three>three</button>
</div>

是否可以返回所有按钮的列表?

即。

constructor() {
  let buttonList = findByElement('button');
}

【问题讨论】:

    标签: javascript html angular


    【解决方案1】:

    使用document.querySelectorAll()

    var div=document.getElementById("div");
    var a=div.querySelectorAll('button');
    console.log(Object.values(a))
    <div id="div">
      <button id="one" #one>one</button>
      <button id="two" #two>two</button>
      <button id="three" #three>three</button>
    </div>

    【讨论】:

    • 这肯定会在整个文档中找到所有内容,而不仅仅是在该组件中?
    • 我想我用document.getElementsByTagName('button');解决了它
    【解决方案2】:

    如果您将RendererElementRef 添加到您的组件,那么您应该能够访问相关元素:

    constructor(private renderer: Renderer, private elem: ElementRef){}
    

    我相信你可以从你的组件中调用:

    const elements = this.elem.nativeElement.querySelectorAll('button');
    

    这将为您提供所需的元素。使用此方法时,确保您在组件初始化后的某个时间点运行代码很重要,而不是像原始代码那样在构造函数中运行,因为我们需要确保我们可以为此访问 DOM零件。 This question 有更多细节。

    【讨论】:

    • elem 的定义是什么?
    • 你必须在 ngAfterViewInit 中调用它,而不是像 OP 那样在构造函数中调用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 2010-10-02
    相关资源
    最近更新 更多