---
title: "Data Selection"
enterprise: true
framework: javascript
version: "14.1.0"
---

# Data Selection

Data Selection allows users click or drag on the chart to mark individual datums as selected. Selected datums receive a distinct visual treatment and can be read back, set, or cleared programmatically.

## Selection

To enable this feature, set `selection.enabled` to `true`.

#### Data Selection

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";
import { getData } from "./data";

ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  title: { text: "Quarterly Revenue" },
  subtitle: { text: "Click or drag to select" },
  selection: {
    enabled: true,
    enableDrag: true,
  },
  data: getData(),
  series: [
    {
      type: "bar",
      xKey: "quarter",
      yKey: "revenue",
      yName: "Revenue ($m)",
      highlight: { enabled: false },
    },
  ],
  axes: {
    x: { type: "category" },
    y: { type: "number" },
  },
  listeners: {
    selectionChange: () => {
      const count = Array.from(chart.getSelection()).length;
      document.getElementById("selectionStatus")!.textContent =
        count === 0
          ? "No items selected"
          : `${count} item${count === 1 ? "" : "s"} selected`;
    },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);
```

[Live example: Data Selection](https://www.ag-grid.com/charts/typescript/selection/examples/selection-basic)

```js
{
    selection: {
        enabled: true,
        enableDrag: true,
    },
}
```

Selection can also be configured independently on each series via the `series.selection` options.

## Click Selection

Click selection is enabled by default. Use `enableClick: false` to disable.

By default, clicking a datum replaces the current selection, and clicking on a blank space clears the selection. Use `clickMode` and `enableClickAwayToClear` to modify this behaviour.

#### Click Modes

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  AgSelectionClickMode,
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";
import { getData } from "./data";

ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  subtitle: { text: "clickMode: 'single', clickAwayToClear: true" },
  selection: {
    enabled: true,
    clickMode: "single",
    enableClickAwayToClear: true,
  },
  data: getData(),
  series: [
    {
      type: "bar",
      xKey: "quarter",
      yKey: "revenue",
      yName: "Revenue ($m)",
      highlight: { enabled: false },
    },
  ],
  axes: {
    x: { type: "category" },
    y: { type: "number" },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);

function setClickMode(value: AgSelectionClickMode) {
  options.selection = { ...options.selection, clickMode: value };
  options.subtitle = {
    text: `clickMode: '${options.selection!.clickMode}', clickAwayToClear: ${options.selection!.enableClickAwayToClear}`,
  };

  chart.update(options);
}

function setClickAway(value: boolean) {
  options.selection = { ...options.selection, enableClickAwayToClear: value };
  options.subtitle = {
    text: `clickMode: '${options.selection!.clickMode}', clickAwayToClear: ${options.selection!.enableClickAwayToClear}`,
  };

  chart.update(options);
}

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

[Live example: Click Modes](https://www.ag-grid.com/charts/typescript/selection/examples/click-modes)

```js
{
    selection: {
        enabled: true,
        clickMode: 'single',
        enableClickAwayToClear: true,
    },
}
```

In the above example:

- `'single'` replaces the current selection with the clicked datum.
- `'multiple'` toggles the clicked datum in or out of the existing selection. This mode is particularly useful on [touch](https://www.ag-grid.com/charts/javascript/touch/) devices.
- Holding `^ Ctrl` key while clicking will always add or remove the clicked datum from the selection.
- When `enableClickAwayToClear` is set to `false`, the selection remains in place when the user clicks an empty area of the chart.
- Click range is determined by the `nodeClickRange` property on each series type.

## Drag-to-Select

Set `enableDrag` to `true` to allow the user draw a rectangle across the chart and select every datum the rectangle covers. This is only available on cartesian series types.

#### Drag Selection

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  AgSelectionContainment,
  BubbleSeriesModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";
import { getData } from "./data";

ModuleRegistry.registerModules([
  BubbleSeriesModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  title: { text: "Drag to select" },
  selection: {
    enabled: true,
    enableDrag: true,
    containment: "any",
  },
  data: getData(),
  series: [
    {
      type: "bubble",
      xKey: "height",
      xName: "Height",
      yKey: "weight",
      yName: "Weight",
      sizeKey: "age",
      sizeName: "Age",
      highlight: { enabled: false },
    },
  ],
  axes: {
    x: { type: "number", title: { text: "Height (cm)" } },
    y: { type: "number", title: { text: "Weight (kg)" } },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);

function setContainment(value: AgSelectionContainment) {
  options.selection = { ...options.selection, containment: value };

  chart.update(options);
}

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

[Live example: Drag Selection](https://www.ag-grid.com/charts/typescript/selection/examples/drag-selection)

```js
{
    selection: {
        enabled: true,
        enableDrag: true,
        containment: 'any',
    },
}
```

In the above example:

- Dragging the mouse across the chart draws a rectangle. When the mouse is released, any datums that overlap the rectangle are selected.
- Holding `^ Ctrl` key while completing a drag adds the newly enclosed datums to the existing selection instead of replacing it.
- The `containment` option controls which datums the drag rectangle picks up.
  - `'any'` (default) selects a datum if any part of it overlaps the drag rectangle.
  - `'all'` selects a datum only when it is entirely enclosed by the drag rectangle.

## Styling

Use the series `series.selection.selectedItem` and `series.selection.unselectedItem` options to customise the appearance of selected and unselected datums.

#### Selection Styling

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";
import { getData } from "./data";

ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  title: { text: "Quarterly Revenue" },
  selection: {
    enabled: true,
    enableDrag: true,
  },
  data: getData(),
  series: [
    {
      type: "bar",
      xKey: "quarter",
      yKey: "revenue",
      yName: "Revenue ($m)",
      highlight: { enabled: false },
      selection: {
        selectedItem: {
          fill: "#c0392b",
          stroke: "#922b21",
          strokeWidth: 3,
        },
        unselectedItem: {
          fill: "#bdc3c7",
          fillOpacity: 0.6,
        },
      },
    },
  ],
  axes: {
    x: { type: "category" },
    y: { type: "number" },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);
```

[Live example: Selection Styling](https://www.ag-grid.com/charts/typescript/selection/examples/selection-styling)

```js
{
    series: [
        {
            type: 'bar',
            xKey: 'quarter',
            yKey: 'revenue',
            selection: {
                selectedItem: {
                    fill: '#c0392b',
                    stroke: '#922b21',
                    strokeWidth: 3,
                },
                unselectedItem: {
                    fill: '#bdc3c7',
                    fillOpacity: 0.6,
                },
            },
        },
    ],
}
```

In this example:

- `selectedItem` sets the selected datum to a red fill and border.
- `unselectedItem` sets the unselected datums to a grey fill.
- For dynamic per-datum styling, use the series [item styler](https://www.ag-grid.com/charts/javascript/stylers/), which includes a `selectionState` property in the parameters.

### Candidacy

The `candidateState` property in [Styler](https://www.ag-grid.com/charts/javascript/stylers/) callbacks can be used to customise the styling while a drag motion is in progress based on the pending selection state.

#### Candidate Styling

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";

ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  title: { text: "Drag the mouse to view custom candidacy styling" },
  selection: {
    enabled: true,
    enableDrag: true,
  },
  data: [
    { category: "A", value: 30 },
    { category: "B", value: 25 },
    { category: "C", value: 40 },
    { category: "D", value: 35 },
  ],
  series: [
    {
      type: "bar",
      xKey: "category",
      yKey: "value",
      itemStyler: (params) => {
        const { candidateState, selectionState } = params;
        // Is this datum included in a drag motion?
        if (
          candidateState === "selected-item" &&
          (selectionState === "unselected-item" || selectionState == "none")
        ) {
          return { fill: "green" };
        }
        // Is this datum excluded from a drag motion?
        if (
          selectionState === "selected-item" &&
          (candidateState === "unselected-item" || candidateState === "none")
        ) {
          return { fill: "red" };
        }
        // No dragging is in progress; Is this datum selected?
        if (selectionState === "selected-item") {
          return { fill: "skyblue" };
        }
        // Default: No dragging is in progress; Not selected.
        return { fill: "gray" };
      },
    },
  ],
  axes: {
    x: { type: "category" },
    y: { type: "number" },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);
```

[Live example: Candidate Styling](https://www.ag-grid.com/charts/typescript/selection/examples/candidate-styling)

In this example:

- When no dragging is in progress:
  - Selected bars are rendered in `'skyblue'` colour.
  - Unselected bars are dimmed.
- When dragging is in progress:
  - Bars that will be added to the selection are rendered in `'green'` colour.
  - Bars that will be removed from the selection are rendered in `'red'` colour.

The `candidateState` property includes:

- `undefined` - no drag selection is in progress.
- `'selected-item'` - the datum will become selected after the drag completes.
- `'unselected-item'` - the datum will become unselected after the drag completes.
- `'none'` - there will be nothing selected after the drag completes.

Once the drag completes, the `candidateState` becomes the new `selectionState`. If the user cancels the drag, the `candidateState` is cleared and the `selectionState` remains unchanged.

## Selection API

#### Selection API

```ts
import {
  AgCartesianChartOptions,
  AgCharts,
  AgSelectionItemIds,
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  ModuleRegistry,
  NumberAxisModule,
  SelectionModule,
} from "ag-charts-enterprise";
import { getData } from "./data";

let savedSelection: AgSelectionItemIds[] = [];
ModuleRegistry.registerModules([
  BarSeriesModule,
  CategoryAxisModule,
  LegendModule,
  NumberAxisModule,
  SelectionModule,
]);

const options: AgCartesianChartOptions = {
  title: { text: "Click bars, then use the buttons above" },
  selection: {
    enabled: true,
    enableDrag: true,
  },
  data: getData(),
  series: [
    {
      type: "bar",
      xKey: "quarter",
      yKey: "revenue",
      yName: "Revenue ($m)",
      highlight: { enabled: false },
    },
  ],
  axes: {
    x: { type: "category" },
    y: { type: "number" },
  },
  listeners: {
    selectionChange: (event) => {
      console.log("selectionChange", {
        source: event.source,
        added: event.added.map((item) => ({
          seriesId: item.seriesId,
          itemId: item.itemId,
        })),
        removed: event.removed.map((item) => ({
          seriesId: item.seriesId,
          itemId: item.itemId,
        })),
      });
    },
  },
};

options.container = document.getElementById("myChart");

const chart = AgCharts.create(options);

function logSelection() {
  console.log("selection", Array.from(chart.getSelection()));
}

function saveSelection() {
  savedSelection = Array.from(chart.getSelection()).map(
    ({ seriesId, itemId }) => ({ seriesId, itemId }),
  );
  console.log("saved", savedSelection.length, "item(s)");
}

function restoreSelection() {
  chart.setSelection(savedSelection);
}

function clearSelection() {
  chart.clearSelection();
}

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

[Live example: Selection API](https://www.ag-grid.com/charts/typescript/selection/examples/selection-api)

### Saving and Restoring

`chart.getSelection()` returns an `Iterable` of every currently selected item. Each item contains:

- `seriesId`- the series the datum belongs to.
- `itemId` - the unique identifier of the datum, derived from `dataIdKey` if set, otherwise the datum index.
- `datum` - the original data object from the chart data array.

`chart.setSelection(items)` replaces the current selection. Each item requires `seriesId` and `itemId` to identify the datum. The existing selection is cleared before the new items are applied.

`chart.clearSelection()` removes every selected item across all series.

### Selection Change Event

The `selectionChange` event fires whenever the selection is updated, whether by user interaction or an API call.

```js
{
    listeners: {
        selectionChange: (event) => {
            console.log(event.source, event.added, event.removed);
        },
    },
}
```

The event contains:

- `source` - `'user-interaction'` or `'api-call'`.
- `added` - an array of items added to the selection.
- `removed` - an array of items removed from the selection.

## Feature Interactions

### Highlighting

When both selection and [highlighting](https://www.ag-grid.com/charts/javascript/series-highlighting/) are enabled, the chart merges their visual styles. If there is a conflict, the selection style takes priority.

### Zoom

When both selection drag and [zoom](https://www.ag-grid.com/charts/javascript/zoom/) drag-to-select (`enableSelecting`) are enabled, the selection drag takes precedence. Zoom panning uses the `panKey` modifier instead. See [Zoom Panning](https://www.ag-grid.com/charts/javascript/zoom/#panning) for details.

## API Reference

#### Selection

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| enabled | boolean | false | Set to `true` to enable the data-selection module. |
| enableClick | boolean | true | Set to `true` to enable click-to-select. |
| enableDrag | boolean | false | Set to `true` to enable drag-to-select. |
| enableClickAwayToClear | boolean | true | Set to `true` to clear the selection by clicking an empty space on the chart. |
| clickMode | 'single' \| 'multiple' | 'single' | Click-to-select mode. `'single'` replaces the current selection; `'multiple'` toggles each click. Holding Control (or Command) temporarily promotes a single click to `'multiple'`. |
| containment | 'any' \| 'all' | 'any' | Drag-to-select containment rule. `'any'` selects a datum when any part overlaps the drag rectangle; `'all'` requires the datum to be fully enclosed. |

#### Series Selection

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| enabled | boolean |  | Set to `true` to enable the data-selection on this series. |
| containment | 'any' \| 'all' | chart.selection.containment | Override the drag-to-select containment rule for this series. |
| selectedItem | AgSelectionStyleOptions |  | Styling options for selected items. |
| selectedItem.opacity | Opacity |  | The opacity of the whole series (line, fill, labels and markers, if any) |
| selectedItem.stroke | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor |  | The colour for the stroke. |
| selectedItem.strokeWidth | PixelSize |  | The width of the stroke in pixels. |
| selectedItem.strokeOpacity | Opacity |  | The opacity of the stroke colour. |
| selectedItem.lineDash | PixelSize[] |  | An array specifying the length in pixels of alternating dashes and gaps. |
| selectedItem.lineDashOffset | PixelSize |  | The initial offset of the dashed line in pixels. |
| selectedItem.fill | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor \| AgGradientColor \| AgPatternColor \| AgImageFill |  | The colour for filling shapes. A colour string, or an object for a gradient, pattern, or image fill. |
| selectedItem.fillOpacity | Opacity |  | The opacity of the fill colour. |
| unselectedItem | AgSelectionStyleOptions |  | Styling options for unselected items. |
| unselectedItem.opacity | Opacity |  | The opacity of the whole series (line, fill, labels and markers, if any) |
| unselectedItem.stroke | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor |  | The colour for the stroke. |
| unselectedItem.strokeWidth | PixelSize |  | The width of the stroke in pixels. |
| unselectedItem.strokeOpacity | Opacity |  | The opacity of the stroke colour. |
| unselectedItem.lineDash | PixelSize[] |  | An array specifying the length in pixels of alternating dashes and gaps. |
| unselectedItem.lineDashOffset | PixelSize |  | The initial offset of the dashed line in pixels. |
| unselectedItem.fill | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor \| AgGradientColor \| AgPatternColor \| AgImageFill |  | The colour for filling shapes. A colour string, or an object for a gradient, pattern, or image fill. |
| unselectedItem.fillOpacity | Opacity |  | The opacity of the fill colour. |
| unselectedSeries | AgSelectionStyleOptions |  | Styling options for series with no selections when there is at least one other selected series. |
| unselectedSeries.opacity | Opacity |  | The opacity of the whole series (line, fill, labels and markers, if any) |
| unselectedSeries.stroke | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor |  | The colour for the stroke. |
| unselectedSeries.strokeWidth | PixelSize |  | The width of the stroke in pixels. |
| unselectedSeries.strokeOpacity | Opacity |  | The opacity of the stroke colour. |
| unselectedSeries.lineDash | PixelSize[] |  | An array specifying the length in pixels of alternating dashes and gaps. |
| unselectedSeries.lineDashOffset | PixelSize |  | The initial offset of the dashed line in pixels. |
| unselectedSeries.fill | CssColor \| AgColorRef \| AgColorRefMixOnto \| AgColorRefMixOntoColor \| AgGradientColor \| AgPatternColor \| AgImageFill |  | The colour for filling shapes. A colour string, or an object for a gradient, pattern, or image fill. |
| unselectedSeries.fillOpacity | Opacity |  | The opacity of the fill colour. |

#### Selection Change Event

| Property | Type | Default | Description |
| --- | --- | --- | --- |
| type (required) | 'selectionChange' |  | Event type. |
| source (required) | 'user-interaction' \| 'api-call' |  | An indication of what triggered this event. |
| added (required) | AgSelectionItem[] |  | Items added to the selection in this change. |
| added.datum (required) | TDatum |  | Datum from the chart or series data array. |
| added.seriesId (required) | string |  | Series ID, as specified in `series.id` (or generated if not specified). |
| added.itemId (required) | string \| number |  | The unique identifier of the datum as specified in `dataIdKey` if set (or generated if not specified). |
| removed (required) | AgSelectionItem[] |  | Items removed from the selection in this change. |
| removed.datum (required) | TDatum |  | Datum from the chart or series data array. |
| removed.seriesId (required) | string |  | Series ID, as specified in `series.id` (or generated if not specified). |
| removed.itemId (required) | string \| number |  | The unique identifier of the datum as specified in `dataIdKey` if set (or generated if not specified). |
| preventDefault (required) | Function |  | Prevent the AG Charts built-in default event handlers from running. |
| context | TContext |  | Callback context for this event. |
