Home > database >  Hide aggrid columns conditionally based on route/query params
Hide aggrid columns conditionally based on route/query params

Time:01-09

I'm using ag-grid version 27.3.0, I have defined colDefs by binding It to HTML [Coldefs]='Coldefs' and I have defined Coldefs in an array in ts file.

binding coldefs in HTML and defining array in .ts file


HTML


TS

Now I'm hiding the columns based on the value of the query params I have stored in ngOnInit(). Still, the issue is since I'm binding the colDefs in HTML colDefs are getting executed first, and then I get query params in a variable.

storing query parms on ngOnInit(), Route: /credit-debit-memo-history?custId=&repId=0&CF=&fdt=0001-01-01&tdt=0001-01-01&type=credit&relCust=


params

How can I access the query params in the colDefs so that I can hide and show the variables based on the query param value?

Not getting values because after colDefs ngOninit will set queryParams


not getting values of params

Note: I can generate colDefs array dynamically but I have over 2K grids in my angular application, it will be a great help if you help me to solve this issue. Thanks.

CodePudding user response:

I figure you have two choices:

  1. Load the grid and then update the grid once you have established query params
  2. Wait to initialise the grid until you have them

I think the simplest way would be to wait to initialise those colDefs until you have the query params.

Instead of defining and setting at the class level, just leave it as public columnDefs: ColDef[] | GroupColDef; (I recall it'll complain at you if you try using only ColDef[] because it accepts two types, and the other type is something like that...).

Then in your query params retrieval you add in an init and copy/paste into there:

        ...
        this.CF = queryParams.CF;
        this.initColDefs(this.queryParams);
        this.preLoadData(this.queryParams);
    });
}

private initColDefs(queryParams: Params): void {
    this.columnDefs = [
        { ... },
        ...
    ];
}

Last piece of the puzzle is to block grid from loading until you have those col defs in place:

<ng-container *ngIf="columnDefs">
    <ag-grid-angular ...>
    </ag-grid-angular>
</ng-container>

CodePudding user response:

You can edit the hide property of the desired column in onGridReady and then use api.setColumnDefs(columns).

setColumnDefs: The grid will redraw all the column headers, and then redraw all of the rows.

onGridReady(params: any) {
   const col = this.columnDefs.find(x=>x.headerName === 'Type')
   col.hide = this.queryParams.type === 'debit'
   params.api.setColumnDefs(this.columnDefs).
}
  • Related