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

如何获取组件的"高度"one_answers"宽度"?

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

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

<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

编辑:
为了清楚起见,使用此解决方案读取元素即可。如果需要操作元素,请确保使用Renderer2https://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

它就像一个符咒。

最新更新