You need to enable JavaScript to run this app. Angular 如何在resize HostListener中获取组件的高度与宽度
优惠活动
大模型
产品
解决方案
定价
更多

Angular 如何在resize HostListener中获取组件的高度与宽度

实现方案

你需要先拿到组件对应的DOM节点,再通过标准DOM API读取宽高即可,完整实现如下:

基础实现步骤

  1. 调整组件内的宽高变量类型,替换原来的空字符串初始值为数值(更适配宽高的数值属性)
  2. 注入ElementRef获取组件的宿主DOM元素
  3. 在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获取模板内的元素引用:

  1. 给模板内的目标元素加模板引用标识:
    <div #measureTarget>需要测量尺寸的内容块</div>
    
  2. 在组件类中获取引用并读取尺寸:
    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 12:36:06