You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Angular mat-table列的像素宽度?

获取Mat-Table指定列的像素宽度

你可以通过直接查询表格的DOM元素来获取列宽度,以下是修改你现有代码的具体步骤:

修改app.component.ts中的getTableWidth方法

将原方法替换为以下代码,即可获取第2列的宽度:

getTableWidth() {
  const table = document.getElementById('myTable');
  if (table) {
    // 获取表头的所有列单元格
    const headerColumns = table.querySelectorAll('thead tr th');
    // 第2列对应索引为1(索引从0开始)
    const targetColumn = headerColumns[1];
    if (targetColumn) {
      // offsetWidth 返回包含边框、内边距和内容的总宽度(单位:px)
      const columnWidth = targetColumn.offsetWidth;
      alert(`第2列的宽度为:${columnWidth}px`);
    } else {
      alert('未找到目标列');
    }
  } else {
    alert('未找到表格元素');
  }
}

补充说明

  • 如果需要获取tbody中单元格的宽度,只需将thead替换为tbody,但表头的宽度通常与整列一致,优先使用表头更可靠。
  • offsetWidth包含元素的内容宽度、内边距和边框;若仅需内容+内边距的宽度,可改用clientWidth。

内容的提问来源于stack exchange,提问作者gnitsuk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 06:10:56