Angular 获取组件的高度和宽度

teu*_*mec 1 angular angular11

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

@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 = '';
Run Code Online (Sandbox Code Playgroud)

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

TMF*_*LGR 6

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

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

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

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

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

组件尺寸:
有一些方法可以获取组件尺寸,但这是一个非常低效的解决方案!!!!!!使用时要小心。底层的 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

}

Run Code Online (Sandbox Code Playgroud)

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

  • 好的解决方案。关于你最后的解决方案;直接访问以读取 DOM 元素应该没问题,除非他正在操纵它们,在这种情况下,正确的方法是使用 `Renderer2` https://angular.io/api/core/Renderer2 (2认同)
  • 是的,阅读是可以的,但不应该使用原生元素进行操作!我会将其添加到我的解决方案中。 (2认同)