Angular项目TS遍历HTMLCollection报ts(2488)错误如何修复
报错原因
document.getElementsByClassName 返回值类型为 HTMLCollectionOf<Element>,如果Angular项目的TS配置没有引入DOM.Iterable类型声明,TS不会识别该类型的[Symbol.iterator]迭代器实现,直接用for...of遍历就会抛出2488类型错误。
另外贴出的原始代码存在生命周期钩子拼写错误:ngOninit 正确写法为 ngOnInit(OnInit的第二个字母i为大写),不修正的话对应逻辑根本不会被框架执行。
可用修复方案
方案1:转数组后遍历(最通用,不用改配置)
用Array.from()把类数组结构的HTMLCollection转成真正的数组,就可以正常用for...of遍历,同时加类型断言避免style属性的类型报错:ngOnInit(): void { const areaDomList = document.getElementsByClassName("some-area"); const areaNum = areaDomList.length; for (const area of Array.from(areaDomList)) { (area as HTMLElement).style.height = `${100 / areaNum}%`; } }方案2:用索引式for循环遍历(无额外转换,兼容性最好)
不依赖迭代器能力,直接通过下标取元素,完全避开迭代器类型校验问题:ngOnInit(): void { const areaDomList = document.getElementsByClassName("some-area"); const areaNum = areaDomList.length; for (let i = 0; i < areaNum; i++) { const area = areaDomList[i] as HTMLElement; area.style.height = `${100 / areaNum}%`; } }方案3:修改TS配置支持DOM迭代
打开项目根目录的tsconfig.json,在compilerOptions的lib数组中添加"DOM.Iterable"配置,保存后TS会自动加载DOM集合的迭代器类型声明,原有的for...of写法就不会再报类型错误。
更符合Angular规范的写法
不推荐直接通过document操作DOM,Angular提供了专门的DOM查询方式,能避免变更检测不触发、SSR渲染异常等问题:
- 先在模板文件里给目标元素加模板引用变量:
<div class="some-area" #targetArea></div> <div class="some-area" #targetArea></div> <!-- 其他同class元素 -->
- 在组件类里用
@ViewChildren获取元素集合,直接遍历即可:
import { Component, OnInit, ViewChildren, ElementRef, QueryList } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html' }) export class DemoComponent implements OnInit { @ViewChildren('targetArea') areaList!: QueryList<ElementRef<HTMLElement>>; ngOnInit(): void { // 如果元素是*ngIf条件渲染的,把这段逻辑移到ngAfterViewInit生命周期里 const areaNum = this.areaList.length; this.areaList.forEach(areaRef => { areaRef.nativeElement.style.height = `${100 / areaNum}%`; }) } }
内容的提问来源于stack exchange,提问作者pixelKus2022
相关产品推荐
相关产品推荐

