如何遍历Angular中ViewChildren对应元素的子元素
问题:动态创建容器后无法遍历子元素集合
使用ngFor动态创建容器时,能通过console.log打印出容器的子元素集合,但调用forEach遍历该集合时无任何输出。不过通过索引访问子元素、使用普通for循环可以正常生效。
模板代码
<ng-container *ngFor="let i of count"> <div #containers> <div> <span>{{'1st div'}}</span> </div> <div> <span>{{'2nd div'}}</span> </mat-chip> <div> <span>{{'3rd div'}}</span> </div> <div> <span>{{'4th div'}}</span> </div> </div> </ng-container>
组件代码
@ViewChildren('containers') containers: QueryList<any>; public ngAfterViewInit() { this.containers.changes.subscribe((containers) => { const firstContainer = containers.toArray()[0]; const childrenArr = firstContainer.nativeElement.children; console.log(childrenArr); // 正常输出 childrenArr.forEach((child) => { console.log(child); // 无任何输出 }); }); }
原因分析
childrenArr是HTMLCollection类型的对象,而非标准JavaScript数组。HTMLCollection属于类数组对象,本身并没有内置forEach方法,因此直接调用childrenArr.forEach不会生效。
解决方法
方法1:转换为标准数组后使用forEach
通过Array.from()将HTMLCollection转换为数组,再调用forEach:
const childrenArr = firstContainer.nativeElement.children; Array.from(childrenArr).forEach(child => { console.log(child); });
方法2:借助Array原型的forEach方法
直接调用Array.prototype.forEach.call来遍历类数组对象:
const childrenArr = firstContainer.nativeElement.children; Array.prototype.forEach.call(childrenArr, child => { console.log(child); });
方法3:使用普通for循环(已验证可行)
通过索引遍历类数组对象:
const childrenArr = firstContainer.nativeElement.children; for (let i = 0; i < childrenArr.length; i++) { console.log(childrenArr[i]); }
内容的提问来源于stack exchange,提问作者inquisitivemongoose
相关产品推荐
相关产品推荐

