【问题标题】:How to loop through a HTMLCollection in an angular app using typescript如何使用打字稿在角度应用程序中循环 HTMLCollection
【发布时间】:2020-06-04 18:10:15
【问题描述】:

我是 Angular 的新手,我正在尝试遍历一个 html 集合,以便我可以获取每个元素的属性,例如 id,但即使在获取集合的数组表示之后它似乎也不起作用如下面的代码所示。我正在使用打字稿来构建一个角度应用程序。有什么解决办法吗?还是我做错了什么?

this.customElements = Array.from(
      document.getElementsByClassName('custom-elem')
    );

    this.customElements.forEach(element => {
      console.log(element);
    });

【问题讨论】:

  • “但它似乎不起作用”是什么意思?

标签: angular typescript htmlcollection


【解决方案1】:

您不必从 HTMLCollection 创建新数组。 getElementsByClassName() 函数默认返回所有子元素的array-like object。所以以下应该工作:

this.customElements = document.getElementsByClassName('custom-elem');

for (const element in this.customElements) {
  console.log(element);
}

工作示例:Stackblitz

【讨论】:

    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2017-06-04
    • 1970-01-01
    相关资源
    最近更新 更多