Search code examples
typescriptenumsag-gridag-grid-ng2ag-grid-angular

How to display enum value in ag-grid cell field value?


I am using ag-grid latest version (^20). I have tried the cell rendering but not sure how to display the string instead of enums.

In sample.component.html code

<ag-grid-angular 
    #agGrid style="width: 100%; height: 350px;" 
    class="ag-theme-balham"
    [gridOptions]="gridOptions"
    [columnDefs]="columnDefs"
    [showToolPanel]="showToolPanel"
    [defaultColDef]="defaultColDef"
    [rowData]="rowData">
</ag-grid-angular>

In sample.component.ts code

 export const PROJECT_LIST_COLUMNS = [
        { headerName: 'Code', field: 'code', width: 120 },
        { headerName: 'Name', field: 'name', width: 200 },
        { headerName: 'Customer', field: 'customerName', width: 200 },
        { headerName: 'Manager', field: 'manager', width: 150 },
        { headerName: 'Project Group', field: 'projectGroup', width: 150 },

        {
            headerName: 'End Date',
            field: 'endDate',
            width: 130,
        },
        {
            headerName: 'Status', //what I want is from the below project status file I want the string 
            field: 'status', 
            width: 150,
            cellRenderer: data => {
                return data.value ? data.value : 'not found';
            },
        },
    ];

And this is my project-status.ts file

export enum ProjectStatus {
    Queue = -3,
    Hold= -2,
    Proposal = -1,
    NS= 0,
    WIP= 1,
    Completed = 2,
    Posted= 3,
    Closed = 4,
}

Not sure how to achieve this. Kindly help


Solution

  • Use ProjectStatus[data.value] to get the text of the enum value.

        {
            headerName: 'Status',
            field: 'status', 
            width: 150,
            cellRenderer: data => {
                return (data.value !== null && data.value !== undefined)
                        ? ProjectStatus[data.value] : 'not found';
            },
        }
    

    Note: Make sure to update your condition as (data.value !== null && data.value !== undefined), otherwise ProjectStatus.NS will show you not found.

    Reference: How does one get the names of TypeScript enum entries?

    Detailed reference:: TypeScript Handbook - Enums

    Reverse mappings

    In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names. For example, in this example:

    enum Enum { A }  
    let a = Enum.A;
    let nameOfA = Enum[a]; // "A"