如何从htmlelement(elementref)获取子宽度

问题描述 投票:0回答:1

我需要从elementref获取所有孩子的宽度。

这些项目是动态加载的

打字稿:

@ViewChild('mainSubMenu') subMenu: ElementRef;

ngAfterViewInit() {
    const greedyNav = this.subMenu.nativeElement;
    let totalSpace = 0;
    let breakWidths = [];
    let itemCount = 0;

   // Loop over all elements and set sum of widths for each menu item
   for (const i of greedyNav.children) {
     totalSpace += greedyNav.children[i].clientWidth;
     breakWidths.push(totalSpace);
     itemCount += 1;
     }
   }

HTML:

   <nav class="sub-nav-tabs">
    <ul class="main-sub-menu" #mainSubMenu>
      <li class="sub-menu-item" *ngFor="let menuItem of menuitems">
        <a class="sub-menu-link">{{menuItem.item}}</a>
      </li>
    </ul>
  </nav>
html angular children elementref
1个回答
0
投票

修改你的方法,如:

ngAfterViewInit() {
    const greedyNav = this.subMenu.nativeElement;
    let totalSpace = 0;
    let breakWidths = [];
    let itemCount = 0;

  // Loop over all elements and set sum of widths for each menu item
  for (const eachChild of greedyNav.children) {
    totalSpace += eachChild.clientWidth;
    breakWidths.push(totalSpace);
    itemCount += 1;
    }
  }

您正在使用of运算符循环您的数组,因此您可以在循环中获取eachChild,而不是索引。

© www.soinside.com 2019 - 2024. All rights reserved.