I want to make the dropdown menu's width be dependent on another element.
The element's width itself is dynamic as I used the responsive-friendly classes on it.
I am using Angular; I tried to bind the width using [style.width.px] but it only works for the first trigger. After closing the dropdown, the width resets to default every other time I open it. Is it not possible to do this?
Please help, thanks.
Check if Angular's change detection in the width resetting. You may need to explicitly trigger change detection after updating the width.
Could you please share your code from the ts file?
Thanks
In Angular, dynamically setting the width of a dropdown menu based on another element's width can be achieved with a combination of Angular template binding and a ViewChild decorator. The issue you're facing might be related to the way you're handling the width binding. Here's a general approach you can follow:
import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, ViewChild } from "@angular/core";
@Component({
selector: "app-your-component",
templateUrl: "./your-component.component.html",
styleUrls: ["./your-component.component.css"]
})
export class YourComponent implements AfterViewInit {
@ViewChild("referenceElement") referenceElement: ElementRef;
constructor(private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
// You may need to add a delay if the referenceElement"s width is not available immediately
setTimeout(() => {
// Set the initial width on component initialization
this.setDropdownWidth();
});
}
getDropdownWidth(): number {
// Calculate and return the width dynamically
return this.referenceElement.nativeElement.offsetWidth;
}
setDropdownWidth(): void {
// Update the dropdown width when needed
// This method can be called whenever the dropdown should update its width
this.cdr.detectChanges();
}
// ... other component logic
}
Hi, Faizal. Thank you for your reply. It still only works the first time the dropdown is triggered.
When inspecting the dropdown menu on the first click trigger with the correct width, seen in the style: (I had to add style_ because of the formatting)
<div data-kt-menu="true" class="menu menu-sub menu-sub-dropdown show" style_="width: 505px; z-index: 105; position: fixed; inset: 0px auto auto 0px; margin: 0px; transform: translate3d(47px, 204px, 0px);" data-popper-placement="top-start">
<div data-kt-menu="true" class="menu menu-sub menu-sub-dropdown" style>
<div data-kt-menu="true" class="menu menu-sub menu-sub-dropdown show" style_="z-index: 105; position: fixed; inset: 0px auto auto 0px; margin: 0px; transform: translate3d(47px, 204px, 0px);" data-popper-placement="top-start">
(window:resize)="onResize($event)"
kt-hidden-width="234"