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