How to get width of (DOM) Element in Angular2

后端 未结 4 1778
栀梦
栀梦 2020-12-15 03:32

there a some similiar threads but I couldn\'t find a suitable answer for my needs. So that direct DOM access should be strictly avoided in angular2 I\'m just wondering whats

4条回答
  •  悲&欢浪女
    2020-12-15 04:00

    I tried out @GünterZöchbauer solution and refined it. You do not need HostListener to get bounds of div. Like with 'click' or other event (event)="function()", it will fire this function. I hope someone will find this helpful.

    onResize() { this.resizeWorks(); } @HostBinding('style.height.px') elHeight:number; private resizeWorks(): void { this.elHeight = this.el.nativeElement.width; }

    (#div) - this is variable needed to get measurement target. It does not have to be same name as element, it can be any name.

    One more way to get element dimensions is to use ElementRef class from Angular Core, but then you have to find that child element which has width and height properties. I used this in Angular 2 Maps to get container width and height, but i found out that, using this method i had to find in element tree element which had these properties and it was second child of root element. It is more messy. ElementDimensions - is just a class with height and width which I made to contain those properties.

    private getContainerDimensions(): ElementDimensions{ var rootElement = this.elementRef.nativeElement; var childElement = rootElement.firstElementChild; var contentElement = childElement.firstElementChild; return { height:contentElement.clientHeight, width: contentElement.clientWidth }; }

提交回复
热议问题