I have implemented a custom directive that appends a dropdown to the body when it is displayed. The logic functions correctly when executed within the ngAfterViewInit
lifecycle, but I encounter issues when attempting to use the same logic within the window.resize
event because the getBoundingClientRect
method does not return accurate values.
@Directive({
selector: '[appendDropdownToBody]'
})
export class AppendDropdownToBodyDirective implements AfterViewInit {
constructor(
private _el: ElementRef,
private _renderer: Renderer2,
private _changeDetectorRef: ChangeDetectorRef
) {}
ngAfterViewInit() {
//Works fine
this.appendToBody();
}
@HostListener('window:resize', ['$event'])
onResize(event: Event) {
//Not working properly
this.appendToBody();
}
private appendToBody() {
const dropdownEl = this._el.nativeElement as HTMLElement;
const parentEl = dropdownEl.parentElement as HTMLElement;
const parentElRect = parentEl.getBoundingClientRect() as DOMRect;
this._renderer.appendChild(document.body, dropdownEl);
this._renderer.setStyle(
dropdownEl,
'top',
parentElRect.bottom + 10 + 'px'
);
this._renderer.setStyle(dropdownEl, 'left', parentElRect.left + 'px');
this._renderer.setStyle(dropdownEl, 'width', parentElRect.width + 'px');
}
}