Iterate Over Columns & Update
Here is a dynamic column width calculation for LWC:
<script type="text/javascript"> // <![CDATA[ class DynamicWidthDatatable { constructor() { this.columns = [ { label: 'Legal Entity Name', fieldName: 'legalEntityName', type: 'text', initialWidth: 100, typeAttributes: { overWriteColumnWidthStyle: "width: 100px;" // Default width } }, { label: 'Other Column', fieldName: 'otherField', type: 'text', initialWidth: 120, typeAttributes: { overWriteColumnWidthStyle: "width: 120px;" } } ]; this.leArray = [ { legalEntityName: "abc 123", otherField: "Sample Data" }, { legalEntityName: "1234567890", otherField: "More Data" } ]; this.calculateColumnWidth(); } calculateColumnWidth() { // Find the longest legalEntityName length let maxLength = Math.max(...this.leArray.map(item => item.legalEntityName.length), 10); // Calculate width dynamically (each character ~8px, min 100px) let calculatedWidth = Math.max(100, maxLength * 8); // Iterate and update only if fieldName === 'legalEntityName' and typeAttributes has overWriteColumnWidthStyle this.columns = this.columns.map(col => { if ( col.fieldName === 'legalEntityName' && col.typeAttributes?.overWriteColumnWidthStyle ) { return { ...col, initialWidth: calculatedWidth, typeAttributes: { ...col.typeAttributes, overWriteColumnWidthStyle: `width: ${calculatedWidth}px;` } }; } return col; }); } } // Instantiate the class to trigger the logic const dynamicWidth = new DynamicWidthDatatable(); console.log(dynamicWidth.columns); // ]]> </script>
Iterate Over Columns & Update
Reviewed by dasfrogpractice
on
05:42
Rating:
No comments: