[SalesForce] How to control the height of datatable dynamically in LWC

I wish to control the height of a datatable based on the number of records present. If there are less than 10 rows, the height of the datatable should be just enough to show all rows. There should also be a minimum and maximum height for the datatable (in case there are 0 rows or more than 20 rows).

I tried using CSS for it, but it's not working.

The below code restricts the height, but it's not dynamic.

    <div style="height: 15rem;">
        <lightning-datatable key-field="Id"
                             columns={tableColumns}
                             data={data}
        </lightning-datatable>
    </div>

Best Answer

After getting data for datatable, store the length in a variable.

Use a JS function to set the height of the datatable dynamically.

HTML Code

<div class="slds-table_col-bordered slds-table_bordered" style={setDatatableHeight}>
     <lightning-datatable key-field="Id" data={validDownloadsData} columns={columns}>
     </lightning-datatable>
</div>

JS Code

//This function controls the height of the datatable based on the number of records.
    get setDatatableHeight() {
        if(this.count==0){//set the minimum height
            return 'height:2rem;';
        }
        else if(this.count>10){//set the max height
                return 'height:50rem;';
        }
        return '';//don't set any height (height will be dynamic)
    }