如何获取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
相关产品推荐
相关产品推荐

