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

时间:2019-04-26 11:29:29

标签: html angular children elementref

我需要从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>

1 个答案:

答案 0 :(得分: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本身,而不是索引。