# Conditional Styling

Canonical page: https://www.adaptabletools.com/docs/handbook-column-formatting-conditions

- Optional **Rules** on Format Column definitions — apply a style or display format only when a cell or row matches
- Most Conditions are change-based (boolean over cell values) but Observable (live history / time) are also supported
- Scoped to specific columns or whole rows
- Conditions use an [Expression](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md) (AdapTableQL)

[Format Columns](https://www.adaptabletools.com/docs/handbook-column-formatting/index.md) can be provided with a [`Rule`](https://www.adaptabletools.com/docs/reference/formatcolumn.md#rule) — which specifies whether or not to render the Format.

This allows users to create very visually striking Grids with a minimum of effort.

Conditions can be applied to both elements of Column Formatting:

- [Display Formats](https://www.adaptabletools.com/docs/handbook-column-formatting-display-format/index.md)
- [AdapTable Style](https://www.adaptabletools.com/docs/handbook-column-formatting-adaptable-style/index.md)

## Expression

The Rule is a Boolean Expression (it must evaluate to true / false), evaluated by [AdapTableQL](https://www.adaptabletools.com/docs/adaptable-ql-expression/index.md).

Expressions are very powerful and can contain multiple criteria and AND / OR logic

Conditions are evaluated in Real Time so Format Columns are applied automatically as Grid data updates.

Format Columns with Conditions are only applied when the cell values satisfy all supplied criteria in the Expression

**Example: Conditional Styles**

Applying Conditional Styles

This example provides 2 conditional Styles:

- A **Row** Condition (`Scope: All`) which highlights the whole Row when `Language` is 'TypeScript'
- A **Column** Condition (`Scope`: a single Column) which colours `Weekly Issue Change` green and bold when the value is positive

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Conditional Style',
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        // Row Condition: style the whole row when the repo uses TypeScript
        {
          Name: 'conditional-row-style',
          Scope: {
            All: true,
          },
          Style: {
            BackColor: '#8fd3fe',
            ForeColor: 'var(--ab-color-palette-17)',
          },
          Rule: '[language] = "TypeScript"',
        },
        // Column Condition: green, bold font for positive weekly changes in a single Column
        {
          Name: 'conditional-column-style',
          Scope: {
            ColumnIds: ['week_issue_change'],
          },
          Style: {
            ForeColor: 'var(--ab-color-palette-19)',
            FontWeight: 'Bold',
          },
          Rule: '[week_issue_change] > 0',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'license',
            'week_issue_change',
            'github_stars',
            'github_watchers',
            'open_issues_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

**Example: Conditional Display Formats**

Applying Conditional Display Formats

This example provides 2 conditional Display Formats:

- A **Column** Condition (`Scope`: a single Column) which abbreviates `GitHub Stars` (e.g. `12.3K`) when the repo has 1,000 or more stars
- A **Data Type** Condition (`Scope`: all number Columns) which displays any negative number in parentheses

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {AdaptableOptions} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Conditional Display Format',
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        // Single Column Condition: abbreviate large star counts (e.g. 12.3K) for popular repos
        {
          Name: 'conditional-column-display-format',
          Scope: {
            ColumnIds: ['github_stars'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 1,
              FractionSeparator: '.',
              IntegerSeparator: ',',
              Multiplier: 0.001,
              Suffix: 'K',
            },
          },
          Rule: '[github_stars] >= 1000',
        },
        // Data Type Condition: show any negative number (all number Columns) in parentheses
        {
          Name: 'conditional-datatype-display-format',
          Scope: {
            DataTypes: ['number'],
          },
          DisplayFormat: {
            Formatter: 'NumberFormatter',
            Options: {
              FractionDigits: 0,
              IntegerSeparator: ',',
              Parentheses: true,
            },
          },
          Rule: '$SCOPE < 0',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'week_issue_change',
            'open_pr_count',
            'closed_pr_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

## Using `$SCOPE`

Sometimes a Format Column's [Column Scope](https://www.adaptabletools.com/docs/dev-guide-columns-scope/index.md) covers more than one column (i.e. it could be a Data Type, or a Column Type, or a list of `ColumnIds`).

When this happens the Rule should not individually include every Column.

Instead, you should use the [$SCOPE AQL Expression Function](https://www.adaptabletools.com/docs/adaptable-ql-expression-advanced-scope-function/index.md).

`$SCOPE` is a stand-in for whichever column in the Scope is being formatted.

- This allows you to create one rule which covers all columns of a type (including ones not yet created)
- e.g. a green font style for all positive numeric columns (or red and parentheses for negative)

**Example: Conditional Styles using $SCOPE**

Green / red numeric formatting using $SCOPE

- This example provides 2 Format Columns, both with a Scope of all `number` columns:
    - **Positive** - `IS_POSITIVE($SCOPE)` paints the cell green and bold
    - **Negative** - `IS_NEGATIVE($SCOPE)` paints the cell red and bold
- The same rules apply to every numeric column - there is no need to list `ColumnIds` or write a separate Expression per column.

- Look at `Weekly Issue Change` for both colours (it has positive and negative values)
- Click the **Add "Total GitHub" Column** button to add a [Calculated Column](https://www.adaptabletools.com/docs/handbook-calculated-column/index.md) - this turns green automatically, because the `$SCOPE` Rule also covers `number` columns created later

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableButton,
  AdaptableOptions,
  CustomToolbarButtonContext,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Conditional Style $SCOPE',
  dashboardOptions: {
    customToolbars: [
      {
        name: 'AddCalcColumn',
        title: 'Calculated Column',
        toolbarButtons: [
          {
            label: 'Add "Total GitHub" Column',
            buttonStyle: {
              variant: 'raised',
              tone: 'info',
            },
            icon: {
              name: 'plus',
            },
            onClick: (
              button: AdaptableButton<CustomToolbarButtonContext>,
              context: CustomToolbarButtonContext
            ) => {
              const {adaptableApi} = context;
              const columnId = 'total_github';
              // Guard so the button can be clicked once (no duplicate columns)
              const alreadyExists = adaptableApi.calculatedColumnApi
                .getCalculatedColumns()
                .some(calcColumn => calcColumn.ColumnId === columnId);
              if (alreadyExists) {
                return;
              }
              adaptableApi.calculatedColumnApi.addCalculatedColumn({
                ColumnId: columnId,
                FriendlyName: 'Total GitHub',
                Expression: '[github_stars] + [github_watchers]',
                CalculatedColumnSettings: {
                  DataType: 'number',
                },
              });
              // Layout has an explicit column list, so make the new column visible
              adaptableApi.layoutApi.addColumnToCurrentLayout(columnId);
            },
          },
        ],
      },
    ],
  },
  initialState: {
    Dashboard: {
      ModuleButtons: ['FormatColumn'],
      PinnedToolbars: ['AddCalcColumn'],
    },
    Theme: {CurrentTheme: 'dark'},
    FormatColumn: {
      FormatColumns: [
        {
          Name: 'positive-numbers',
          Scope: {
            DataTypes: ['number'],
          },
          Style: {
            ForeColor: 'var(--ab-color-palette-19)',
            FontWeight: 'Bold',
          },
          Rule: 'IS_POSITIVE($SCOPE)',
        },
        {
          Name: 'negative-numbers',
          Scope: {
            DataTypes: ['number'],
          },
          Style: {
            ForeColor: 'var(--ab-color-palette-30)',
            FontWeight: 'Bold',
          },
          Rule: 'IS_NEGATIVE($SCOPE)',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          Name: 'Standard Layout',
          TableColumns: [
            'name',
            'language',
            'week_issue_change',
            'github_stars',
            'github_watchers',
            'open_issues_count',
            'open_pr_count',
          ],
          AutoSizeColumns: true,
        },
      ],
    },
  },
};
```

## Observable Conditions

In addition to standard change-based Conditions, AdapTable also supports [Observable Condition](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions-observable/index.md)

- These are evaluated using a live Observable Expression (history / time) and the cell is formatted if it returns true
- e.g. to format a cell where price is unchanged in 5 seconds use: `NO_CHANGES{[price], WITHIN(5s)}`

### FAQ

**Do I have to provide a Condition?**
No, Formats can be applied across all cells in all columns in Scope without any Condition being supplied (choose **No Condition** in the Wizard).

**What is the difference between Standard and Observable Conditions?**
**Standard** is a boolean over current cell / row values. **Observable** reads change history or time (e.g. stale cells, busy windows). See [Observable Format Column Conditions](https://www.adaptabletools.com/docs/handbook-column-formatting-conditions-observable/index.md).
