---
title: "Context"
framework: javascript
version: "36.1.0"
---

# Context

This sections covers how shared contextual information can be passed around the grid.

## Overview

The context object is passed to all callbacks and events used in the grid. The purpose of the context object is to allow the client application to pass details to custom callbacks such as the [Cell Renderers](https://www.ag-grid.com/javascript-data-grid/component-cell-renderer/) and [Cell Editors](https://www.ag-grid.com/javascript-data-grid/cell-editing/).

| Property | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `context` | `any` |  |  | Provides a context object that is provided to different callbacks the grid uses. Used for passing additional information to the callbacks used by your application. [Initial](https://www.ag-grid.com/javascript-data-grid/grid-interface/#initial-grid-options). |

To update the context call `api.setGridOption` with the new context. Alternatively, if you maintain a reference to the context object it's values can be mutated directly.

## Context Object Example

The example below demonstrates how the context object can be used. Note the following:

- Selecting the reporting currency from the dropdown places it in the context object.
- When the reporting currency is changed the cell renderer uses the currency supplied in the context object to calculate the value using: `params.context.reportingCurrency`.
- The price column header is updated to show the selected currency using a header value getter using `ctx.reportingCurrency`.

#### Context Object

```ts
import {
  ClientSideRowModelModule,
  ColDef,
  GridApi,
  GridOptions,
  HighlightChangesModule,
  ICellRendererParams,
  ModuleRegistry,
  RenderApiModule,
  ValueGetterParams,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  RenderApiModule,
  HighlightChangesModule,
  ClientSideRowModelModule,
]);

const gbpFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "GBP",
  minimumFractionDigits: 2,
});
const eurFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "EUR",
  minimumFractionDigits: 2,
});
const usdFormatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "USD",
  minimumFractionDigits: 2,
});

const currencyComparator = (a: any, b: any) => {
  return a.amount - b.amount;
};

const currencyCellRenderer = (params: ICellRendererParams) => {
  switch (params.value.currency) {
    case "EUR":
      return eurFormatter.format(params.value.amount);
    case "USD":
      return usdFormatter.format(params.value.amount);
    case "GBP":
      return gbpFormatter.format(params.value.amount);
  }
  return params.value.amount;
};

const columnDefs: ColDef[] = [
  { field: "product" },
  { headerName: "Currency", field: "price.currency" },
  {
    headerName: "Price Local",
    field: "price",
    cellRenderer: currencyCellRenderer,
    comparator: currencyComparator,
    cellDataType: false,
  },
  {
    headerName: "Report Price",
    field: "price",
    cellRenderer: currencyCellRenderer,
    comparator: currencyComparator,
    valueGetter: reportingCurrencyValueGetter,
    headerValueGetter: "ctx.reportingCurrency",
  },
];

let gridApi: GridApi;

const gridOptions: GridOptions = {
  columnDefs: columnDefs,
  defaultColDef: {
    flex: 1,
    enableCellChangeFlash: true,
  },
  rowData: getData(),
  context: {
    reportingCurrency: "EUR",
  },
};

function reportingCurrencyValueGetter(params: ValueGetterParams) {
  // Rates taken from google at time of writing
  const exchangeRates: Record<string, any> = {
    EUR: {
      GBP: 0.72,
      USD: 1.08,
    },
    GBP: {
      EUR: 1.29,
      USD: 1.5,
    },
    USD: {
      GBP: 0.67,
      EUR: 0.93,
    },
  };

  const price = params.data[params.colDef.field!];
  const reportingCurrency = params.context.reportingCurrency;
  const fxRateSet = exchangeRates[reportingCurrency];
  const fxRate = fxRateSet[price.currency];
  let priceInReportingCurrency;
  if (fxRate) {
    priceInReportingCurrency = price.amount * fxRate;
  } else {
    priceInReportingCurrency = price.amount;
  }

  const result = {
    currency: reportingCurrency,
    amount: priceInReportingCurrency,
  };

  return result;
}

function currencyChanged() {
  const value = (document.getElementById("currency") as any).value;
  gridApi.setGridOption("context", { reportingCurrency: value });
  gridApi!.refreshCells();
  gridApi!.refreshHeader();
}

function getData() {
  return [
    { product: "Product 1", price: { currency: "EUR", amount: 644 } },
    { product: "Product 2", price: { currency: "EUR", amount: 354 } },
    { product: "Product 3", price: { currency: "GBP", amount: 429 } },
    { product: "Product 4", price: { currency: "GBP", amount: 143 } },
    { product: "Product 5", price: { currency: "USD", amount: 345 } },
    { product: "Product 6", price: { currency: "USD", amount: 982 } },
  ];
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).currencyChanged = currencyChanged;
}
```

[Live example: Context Object](https://www.ag-grid.com/examples/context/context/typescript)

## Context & Expressions Example

Below shows a complex example making use of value getters (using expressions) and class rules (again using expressions). The grid shows 'actual vs budget data and yearly total' for widget sales split by city and country.

- The **Location** column is showing the aggregation groups, grouping by city and country.
- The **Monthly Data** columns are affected by the context. Depending on the selected period, the data displayed is either actual (`x_act`) or budgeted (`x_bud`) data for the month (eg. `jan_act` when Jan is green, or `jan_bud` when Jan is red). Similarly, the background color is also changed using class rules dependent on the selected period.
- **sum(YTD)** is the total of the 'actual' figures, i.e. adding up all the green. This also changes as the period is changed.

Notice that the example (including calculating the expression on the fly, the grid only calculates what's needed to be displayed) runs very fast (once the data is loaded) despite having over 6,000 rows.

This example is best viewed by opening it in a new tab.

#### Monthly Sales

```ts
import {
  CellStyleModule,
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  GridApi,
  GridOptions,
  ICellRendererParams,
  ModuleRegistry,
  QuickFilterModule,
  RenderApiModule,
  RowSelectionModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import {
  FiltersToolPanelModule,
  RowGroupingModule,
  SetFilterModule,
} from "ag-grid-enterprise";

// Enable extended validations only for development
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

ModuleRegistry.registerModules([
  ClientSideRowModelApiModule,
  RenderApiModule,
  RowSelectionModule,
  CellStyleModule,
  QuickFilterModule,
  ClientSideRowModelModule,
  FiltersToolPanelModule,
  RowGroupingModule,
  SetFilterModule,
]);

const monthValueGetter =
  '(ctx.month < ctx.months.indexOf(colDef.field)) ? data[colDef.field + "_bud"] : data[colDef.field + "_act"]';
const monthCellClassRules = {
  "cell-act": "ctx.month < ctx.months.indexOf(colDef.field)",
  "cell-bud": "ctx.month >= ctx.months.indexOf(colDef.field)",
  "cell-negative": "x < 0",
};
const yearToDateValueGetter =
  'var total = 0; ctx.months.forEach( function(monthName, monthIndex) { if (monthIndex<=ctx.month) { total += data[monthName + "_act"]; } }); return total; ';
const accountingCellRenderer = function (params: ICellRendererParams) {
  if (params.value == null) {
    return "";
  } else if (params.value >= 0) {
    return params.value.toLocaleString();
  } else {
    return "(" + Math.abs(params.value).toLocaleString() + ")";
  }
};

const columnDefs: (ColDef | ColGroupDef)[] = [
  {
    field: "country",
    rowGroup: true,
    hide: true,
  },
  {
    headerName: "Monthly Data",
    children: [
      {
        field: "jan",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        field: "feb",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        field: "mar",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        field: "apr",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        field: "may",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        field: "jun",
        cellRenderer: accountingCellRenderer,
        cellClass: "cell-figure",
        valueGetter: monthValueGetter,
        cellClassRules: monthCellClassRules,
        aggFunc: "sum",
      },

      {
        headerName: "YTD",
        cellClass: "cell-figure",
        cellRenderer: accountingCellRenderer,
        valueGetter: yearToDateValueGetter,
        aggFunc: "sum",
      },
    ],
  },
];

let gridApi: GridApi;
const context = {
  month: 0,
  months: [
    "jan",
    "feb",
    "mar",
    "apr",
    "may",
    "jun",
    "jul",
    "aug",
    "sep",
    "oct",
    "nov",
    "dec",
  ],
};
const gridOptions: GridOptions = {
  columnDefs: columnDefs,
  suppressMovableColumns: true,
  defaultColDef: {
    flex: 1,
    minWidth: 120,
  },
  autoGroupColumnDef: {
    headerName: "Location",
    field: "city",
    minWidth: 260,
    cellRenderer: "agGroupCellRenderer",
  },
  rowSelection: {
    mode: "multiRow",
    headerCheckbox: false,
    groupSelects: "descendants",
  },
  context: context,
};

const monthNames = [
  "Budget Only",
  "Year to Jan",
  "Year to Feb",
  "Year to Mar",
  "Year to Apr",
  "Year to May",
  "Year to Jun",
  "Year to Jul",
  "Year to Aug",
  "Year to Sep",
  "Year to Oct",
  "Year to Nov",
  "Full Year",
];

function onChangeMonth(i: number) {
  let newMonth = (context.month += i);

  if (newMonth < -1) {
    newMonth = -1;
  }
  if (newMonth > 5) {
    newMonth = 5;
  }
  // Mutate the context object in place
  context.month = newMonth;
  document.querySelector("#monthName")!.textContent = monthNames[newMonth + 1];
  gridApi!.refreshClientSideRowModel("aggregate");
  gridApi!.refreshCells();
}

function onQuickFilterChanged() {
  gridApi!.setGridOption(
    "quickFilterText",
    (document.getElementById("filter-text-box") as HTMLInputElement).value,
  );
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/monthly-sales.json")
  .then((response) => response.json())
  .then(function (data) {
    gridApi!.setGridOption("rowData", data);
  });

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).onChangeMonth = onChangeMonth;
  (<any>window).onQuickFilterChanged = onQuickFilterChanged;
}
```

[Live example: Monthly Sales](https://www.ag-grid.com/examples/context/monthly-sales/typescript)
