Angular 如何在resize HostListener中获取组件的高度与宽度
实现方案
你需要先拿到组件对应的DOM节点,再通过标准DOM API读取宽高即可,完整实现如下:
基础实现步骤
- 调整组件内的宽高变量类型,替换原来的空字符串初始值为数值(更适配宽高的数值属性)
- 注入
ElementRef获取组件的宿主DOM元素 - 在resize监听方法中调用DOM API读取对应宽高
示例代码:
import { Component, ElementRef, HostListener } from '@angular/core'; @Component({ // 组件原有装饰器配置 }) export class ResizableComponent { theHeight = 0; theWidth = 0; // 注入组件宿主元素引用 constructor(private el: ElementRef<HTMLElement>) {} @HostListener('window:resize') public detectResize(): void { const nativeEl = this.el.nativeElement; // 读取组件的宽高 this.theHeight = nativeEl.offsetHeight; this.theWidth = nativeEl.offsetWidth; } }
可选的宽高读取方式
你可以根据实际测量需求选择对应API:
offsetHeight/offsetWidth:返回元素整体尺寸,包含内容、内边距、边框,结果为整数clientHeight/clientWidth:返回元素可视内容尺寸,包含内容、内边距,不包含边框、垂直滚动条getBoundingClientRect():返回元素的精确布局尺寸(浮点数,适配页面缩放场景),同时可获取元素相对视口的坐标,用法示例:const rect = nativeEl.getBoundingClientRect(); this.theHeight = rect.height; this.theWidth = rect.width;
测量组件内部指定元素的方法
如果需要测量的是组件内部的某一个子元素(而非组件根宿主元素),可以通过@ViewChild获取模板内的元素引用:
- 给模板内的目标元素加模板引用标识:
<div #measureTarget>需要测量尺寸的内容块</div> - 在组件类中获取引用并读取尺寸:
import { ViewChild, ElementRef } from '@angular/core'; // 绑定模板内的元素引用 @ViewChild('measureTarget') measureTargetRef!: ElementRef<HTMLDivElement>; @HostListener('window:resize') public detectResize(): void { // 校验引用存在后再读取,避免视图未初始化时报错 if (this.measureTargetRef) { this.theHeight = this.measureTargetRef.nativeElement.offsetHeight; this.theWidth = this.measureTargetRef.nativeElement.offsetWidth; } }
内容的提问来源于stack exchange,提问作者teumec
相关产品推荐
相关产品推荐

