Angular获取组件的高度和宽度

Angular Get Height and Width of the component

我有一个手动调整大小的组件,所以我添加了一个侦听器:

@HostListener('window:resize')
  public detectResize(): void {
    // get height and width of the component
    this.theHeight = // the coponent height
    this.theWidth = // the coponent height
  }

 theHeight = '';
 theWidth = '';

如何获取组件的高度和宽度?

您的代码正在监听 window 对象,因此您只能获取 window innerHeight 和 innerWidth。有 2 种解决方案可以获取当前的 window 高度。

获取 Window 尺码

事件绑定:

<div (window:resize)="onResizeHandler($event)">...</div>
public onResizeHandler(event): void {
   event.target.innerWidth;
   event.target.innerHeight;
}

Host Listener Decorator:(更简洁的方法!)

@HostListener('window:resize', ['$event'])
onResizeHandler(event: Event): void {
   event.target.innerWidth;
   event.target.innerHeight;
}

组件尺寸:
有一些方法可以获取组件大小,但这是一个非常低效的解决方案!!!!!!使用时要小心。底层 NativeElement Api 将直接访问 DOM! https://angular.io/api/core/ElementRef

编辑:
需要明确的是,使用此解决方案读取元素就可以了。 如果您需要操作您的元素,请务必使用 Renderer2 https://angular.io/api/core/Renderer2

// Inject a element reference into your component constuctor
...
constructor(private elementRef: ElementRef) {...}

// implement a listener on window:resize and attach the resize handler to it
public onResizeHandler(): void {
    this.elementRef.nativeElement.offsetHeight
    this.elementRef.nativeElement.offsetWidth

}

如果您只想在调整大小事件中更改样式 请务必在 css/scss 中使用@media Queries。 这将是最好的方式!

您需要编写自己的代码来检测元素大小的变化。或者您可以使用图书馆 - 就个人而言,我推荐这个:

https://www.npmjs.com/package/angular-resize-event

它就像一个魅力。