0

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

1 回答 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 本身,而不是索引。

于 2019-04-26T11:35:54.310 回答