Angular获取组件的高度和宽度

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

@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 = '';

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

回答

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

获取窗口大小
Angular 窗口大小调整事件事件
绑定:

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

主机监听器装饰器:(更简洁的方法!)

@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。这将是最好的方法!

  • good solution. with regard to your last solution; direct access in order to just read DOM elements should be fine unless he's manipulating them in which case the correct approach would be using `Renderer2` https://angular.io/api/core/Renderer2
  • yes, reading is ok, whilst manipulation should not be done using the native element! i'll add this in my solution.

以上是Angular获取组件的高度和宽度的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>