如何获取ag-grid中的列宽

问题描述 投票:0回答:1

我在我的应用程序中使用ag-grid。我想做的是,如果列标题对于单行来说太大,则将其换行。为此,我必须重新调整标题的高度。我能做到。然而,我需要做的是在渲染后访问列宽。我花了几个小时,但没有运气。这是我一直在使用的一些代码:

    calculateDynamicHeaderHeight() {
        const columnDefs = this.columns;
        const gridApi = this.gridOptions.api;
        let maxHeight = 0;
        const tempDiv = document.createElement('div');

        // Apply similar styles as your header cells
        tempDiv.style.position = 'absolute';
        tempDiv.style.visibility = 'hidden';
        tempDiv.style.whiteSpace = 'normal';
        tempDiv.style.fontSize = '12px'; // Example font size, adjust as needed
        tempDiv.style.lineHeight = '15px'; // Adjust line height as needed
        tempDiv.style.padding = '0';
        tempDiv.style.margin = '0';
        tempDiv.style.boxSizing = 'border-box';

        // Add any additional styles that your headers have

        document.body.appendChild(tempDiv);

        columnDefs.forEach(colDef => {
            // Set the width of the temporary div to the column width
        
            //  This:
        const colWidth = colDef.width;
        // or this:
            const colWidth = gridApi.getColumnDef(colDef.field).actualWidth;
        
            tempDiv.style.width = `${colWidth}px`;

            // Set the header title as the inner HTML
            tempDiv.innerHTML = colDef.headerName;

            console.log(tempDiv.offsetHeight);
            maxHeight = Math.max(maxHeight, tempDiv.offsetHeight);
        });
        console.log('');

        document.body.removeChild(tempDiv); // Remove the tempDiv after the loop

        gridApi.setHeaderHeight(maxHeight + 15);
        return maxHeight + 15;
    }

此代码确实设置了列标题高度。问题是我似乎无法访问列宽。我尝试了上面两行。第一次始终返回 15。第二个无效。我不知道如何获取列宽。任何帮助都将不胜感激!

谢谢!

ag-grid
1个回答
0
投票

我想通了。跳过所有代码。只需将

wrapHeaderText: true
添加到您的列定义中即可。

© www.soinside.com 2019 - 2024. All rights reserved.