'ag-grid column not automatically resizing in angular

I am trying to fix the sizing of the columns issue on the ag-grid in angular 7 application. I have been trying several options as suggested but not getting a solution. What I am looking for is that the columns should automatically resize and take the width of the screen. At the moment when it is rendering for the first time, the last column gets slightly hidden. The second problem that I have is when I reload the grid with data while navigating from another component to this page, the grid width change drastically.

I have tried to add resize attribute on every column as well and also set the suppressSizeToFit: false with min-width and maxWidth defined.

Initial load

enter image description here

Reload of the grid while navigating from another component

enter image description here

html

    <div class="form-group row">
      <div class="panel panel-default col-md-12">
        <div *ngIf="AllocationDetails && AllocationDetails.ManagerAllocations" class="panel-body">
          <div [style.height.px]="GridHeight()" [style.width.%]="100" style="float: left;">
            <span style="text-decoration: underline; cursor: pointer;padding-right: 10px;"><a (click)="expandAll()">Expand
                All</a></span>
            <span style="text-decoration: underline; cursor: pointer;"><a (click)="collapseAll()">Collapse
                All</a></span>
            <ag-grid-angular #agGrid class="ag-theme-balham" [gridOptions]="GridOptions" style="width: 100%; height: 100%"
              [columnDefs]="ColumnDefs" [rowData]="AllocationDetails.ManagerAllocations" rowHeight="30" headerHeight="30"
              rowSelection="single" [pinnedBottomRowData]="pinnedBottomRowData"
              [frameworkComponents]="frameworkComponents">
            </ag-grid-angular>
          </div>

        </div>
      </div>
    </div>

component

    export class AllocationsComponent implements OnInit {


      constructor(private allocationsService: AllocationsService, private comparator: Comparator,
            private zone: NgZone, private route: ActivatedRoute, private spinner: NgxSpinnerService) {
            this.Comparator = comparator;
            this.Route = route;

            window.onresize = (e) => {
                this.ngZone.run(() => {
                    this.windowHeight = window.innerHeight - this.offset;
                    setTimeout(() => {
                        if (!this.GridOptions || !this.GridOptions.api) {
                            return;
                        }
                        this.GridOptions.api.sizeColumnsToFit();
                    }, 500, true);
                });
            };
        }


        setGridOptions() {
            this.GridOptions = {
                columnDefs: this.getColumns(),
                enableFilter: true,
                treeData: true,
                enableColResize: true,
                animateRows: true,
                groupDefaultExpanded: 1,
                enableSorting: true,
                suppressAggFuncInHeader: false,

                getDataPath: function (data) {
                    return data.Hierarchy;
                },
                onGridReady: e => {
                    if (!e || !e.api) {
                        return;
                    }
                    e.api.sizeColumnsToFit();
                    this.setDefaultSortOrder();
                },
                getRowStyle: (params) => {
                    if (params.node.level === 0) {
                        return { 'background-color': '#FCE7D7' };
                    } else if (params.node.level === 1) {
                        return { 'background-color': '#f4f4f4' };
                    }
                },

                autoGroupColumnDef: {
                    headerName: 'Manager Strategy', width: 300,
                    valueFormatter: uniqueColumn
                },

            };
            function uniqueColumn(params) {
                if (params && params.value != null) {
                const startIndex = params.value.indexOf('#');

                if (startIndex === -1) { return params.value; }

                const endIndex = params.value.length;
                return params.value.replace(params.value.substring(startIndex, endIndex), '');
                }

            }
        }

    ngOnInit() {

            this.evalDate = new Date();
            this.setGridOptions();
            this.getAllocationsDetails(this.FormattedDate(this.evalDate));


        }

         GridHeight() {
            if (!this.windowHeight) {
                this.windowHeight = window.innerHeight - this.offset + 10;
            }
            return this.windowHeight;
        }

         private getColumns(): Array<any> {
            const self = this;
            const columnDefs = new Array<any>();
            // const definition = [
                columnDefs.push({ headerName: 'Date', field: 'EvalDate', hide: true});
            columnDefs.push({ headerName: 'Firm ID', field: 'FirmID', hide: true });
            columnDefs.push({ headerName: 'Manager Strategy ID', field: 'FirmName', hide: true });
            columnDefs.push({ headerName: 'Firm', field: 'ManagerStrategyID', hide: true });
            columnDefs.push({ headerName: 'Manager Strategy', field: 'ManagerStrategyName', hide: true });
            columnDefs.push({ headerName: 'Fund ID', field: 'ManagerFundID', hide: true });
            columnDefs.push({ headerName: 'Fund', field: 'ManagerFundName', hide: true });
            columnDefs.push({ headerName: 'Product Name', field: 'ProductName', hide: true });
            columnDefs.push({
                headerName: 'As Of', field: 'EvalDate',
                cellStyle: { textAlign: 'right' },
                hide: false
                ,  width: 150, minWidth: 200, maxWidth: 300, suppressSizeToFit: false
            });
            columnDefs.push({
                headerName: 'EMV (USD)', field: 'UsdEmv', valueFormatter: this.currencyFormatter, rowGroup: false,
                cellRenderer: 'agGroupCellRenderer',
                aggFunc: 'sum',
                cellStyle: { textAlign: 'right' },
                pinnedRowCellRenderer: "customPinnedRowRenderer", pinnedRowCellRendererParams: { style: { "font-weight": "bold" }}
                ,  resizable :true
            });
            columnDefs.push({
                headerName: '% of Fund Strategy', field: 'GroupPercent', valueFormatter: this.formatPercent, rowGroup: false,
                cellRenderer: 'agGroupCellRenderer',
                aggFunc: 'sum',
                cellStyle: { textAlign: 'right' },
                pinnedRowCellRenderer: "customPinnedRowRenderer", pinnedRowCellRendererParams: { style: { "font-weight": "bold" } }
                ,  width: 150, minWidth: 200, maxWidth: 300, suppressSizeToFit: false
            });
            columnDefs.push({
                headerName: '% of Product', field: 'WeightWithEq',
                valueFormatter: this.formatPercent,
                cellStyle: { textAlign: 'right' }
                ,  width: 150, minWidth: 200, maxWidth: 300, suppressSizeToFit: false
            });



        this.pinnedBottomRowData = this.createData();
        this.frameworkComponents = { customPinnedRowRenderer: CustomPinnedRowRenderer };

        return columnDefs;
    }

    }


Solution 1:[1]

This is what you should do,

On your HTML,

<div id="div_grid">
  <ag-grid-angular #grid ...bunch of code here...
                   [enableColResize]="true"
                   (gridReady)="onGridReady($event)"></ag-grid-angular>
</div>

On your TS,

private gridApi: GridApi;
constuctor(
  // bunch of code
  private elem: ElementRef,
){
  // bunch of code
}

onGridReady(params) {
    // bunch of code
    this.gridApi = params.api;
    this.sizeColumnsToFit();
}

sizeColumnsToFit() {
    const container = this.elem.nativeElement.querySelectorAll('#div_grid');
    if (container[0] && container[0].clientWidth > this.gridWidth && this.gridApi) {
      this.gridApi.sizeColumnsToFit();
    }
}

Assign value to this.gridWidth your total columns width when you work with columnsdefs.

Enjoy!!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1