I have this dropdown and I need to get the width of all items, compare it and get the biggest one. How we can do this in Angular ?
I tried with offsetWidth but I get only one width of this 4 elements and every time it's changing .
<div >
<div [ngStyle]="{'width': megaMenuWidthContainer 'px'}">
<a (click)="toggleActive(item, itemEl, i)"
[routerLink]="itemEl.link | localize"
*ngFor="let itemEl of item.submenu">
<div (click)="addActiveClass(itemEl, i)">
<img
[src]="itemEl?.icon?.path"
[transform]="['resize:fit:20:20', 'q:100']"
/>
<img
[src]="itemEl?.activeIcon?.path"
[transform]="['resize:fit:20:20', 'q:100']"
/>
</div>
<span id="megaMenuContainer" #megaMenuContainer (click)="addActiveClass(itemEl, i)" > {{ itemEl.title }}</span>
</a>
</div>
</div>
CodePudding user response:
Many ways to do this, either directly in template or querying the elements. Not knowing why you need this I'm going to pick the latter option and query all the elements and then find the widest one of them. And I'm exactly not sure which item we're looking for so lets find the <a>
tag elements, for example.
Let's add #findElem
tag to we know we will query these elements.
<a #findElem (click)="toggleActive(item, itemEl, i)"
[routerLink]="itemEl.link | localize"
*ngFor="let itemEl of item.submenu">
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterViewInit {
@ViewChildren('findElem') findElemList: QueryList<ElementRef>;
ngAfterViewInit() {
if (this.findElemList) {
let widestElem;
for (let item of this.findElemList) {
if (!widestElem) {
widestElem = item.nativeElement;
} else if (widestElem.offsetWidth < item.nativeElement.offsetWidth) {
widestElem = item.nativeElement;
}
}
if (widestElem) {
console.log('widest elem is: ', widestElem, ' width px is: ', widestElem.offsetWidth)
}
}
}
}
Feel free to refactor this here and there to find your elements.
Working example: https://stackblitz.com/edit/angular-ivy-vuk3h7?file=src/app/app.component.ts
CodePudding user response:
this line of code show you the size of a div
<div #container>Container's width is {{ container.offsetWidth }}</div>