# Angular Sparkline Component

Sparkline is a word-sized chart in pure SVG for table cells, cards and KPIs: a line, an area, bars with negative values, wins and losses or a bullet chart, with markers, a reference line, a tooltip, keyboard navigation and a text summary for screen readers. It is rendered on the server and has no dependency.

## Basic

Sparkline draws its data , an array of numbers, as a small chart the size of a word, in pure SVG. It is 6em wide and 1.5em high by default, so it follows the font size of the text around it; width and height take any CSS length or a number of pixels, and the chart stretches to any width, 100% included. It is rendered on the server.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';

@Component({
    template: `
        <div class="card flex flex-col gap-4">
            <p class="m-0">Weekly downloads <p-sparkline [data]="data" ariaLabel="Weekly downloads" /> 2,410 this week.</p>
            <p class="m-0 text-2xl">Larger text <p-sparkline [data]="data" ariaLabel="Weekly downloads, larger" /> grows with it.</p>
            <p-sparkline [data]="data" width="100%" height="4rem" ariaLabel="Weekly downloads, full width" />
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineBasicDemo {
    data = [1210, 1340, 1180, 1520, 1610, 1490, 1870, 1760, 2050, 1980, 2240, 2410];
}
```

## Types

type picks the chart. line is the default and area fills below the line, down to zero when the values cross it. bar draws a bar per value from the zero line, the negative values below it in their own color. winloss only shows the sign of each value, a bar up for a win and down for a loss, whatever its size. bullet compares the last value, the bar, to a target given by referenceLine , on qualitative bands set by ranges . The scale runs from the smallest to the largest value, from 0 for bars and bullet charts; min and max fix it, for example to compare the rows of a table on the same scale. curve set to smooth draws a monotone curve, that never goes above or below the values. A null value leaves a gap in the line.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';

@Component({
    template: `
        <div class="card">
            <ul class="list-none m-0 p-0 grid gap-4" style="grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr))">
                <li class="flex items-center justify-between gap-4">
                    <span>Line</span>
                    <p-sparkline [data]="data" width="8rem" height="2rem" ariaLabel="Line" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Smooth line with a gap</span>
                    <p-sparkline [data]="gaps" curve="smooth" width="8rem" height="2rem" ariaLabel="Smooth line with a gap" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Area</span>
                    <p-sparkline [data]="data" type="area" width="8rem" height="2rem" ariaLabel="Area" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Bar</span>
                    <p-sparkline [data]="profit" type="bar" width="8rem" height="2rem" ariaLabel="Bar" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Win-loss</span>
                    <p-sparkline [data]="results" type="winloss" width="8rem" height="2rem" ariaLabel="Win-loss" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Bullet</span>
                    <p-sparkline [data]="[68]" type="bullet" [referenceLine]="80" [ranges]="[50, 75, 100]" width="8rem" height="1.25rem" ariaLabel="Bullet" />
                </li>
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineTypesDemo {
    data = [5, 9, 7, 12, 10, 14, 11, 16, 13, 18];

    gaps = [5, 9, 7, 12, null, null, 11, 16, 13, 18];

    profit = [4, -2, 6, 3, -5, 7, 2, -1, 5, 8];

    results = [1, 1, -1, 1, -1, -1, 1, 1, 1, -1, 1, 1];
}
```

## In a Table

In a table, a sparkline shows a trend per row next to the figures. It needs no observer, no canvas and no timer: each one is a few SVG paths computed once per data change, and listens to the pointer only while the tooltip is on. The table below has 100 rows, one line and one bar chart each, and min and max are left to scale every row on its own.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';
import { TableModule } from '@exhaustive-ui/core/table';

interface Stock {
    symbol: string;
    price: number;
    history: number[];
    change: number[];
}

@Component({
    template: `
        <div class="card">
            <p-table [value]="stocks" [paginator]="true" [rows]="10" [tableStyle]="{ 'min-width': '32rem' }">
                <ng-template #header>
                    <tr>
                        <th>Symbol</th>
                        <th>Price</th>
                        <th>Last 30 days</th>
                        <th>Daily change</th>
                    </tr>
                </ng-template>
                <ng-template #body let-stock>
                    <tr>
                        <td>{{ stock.symbol }}</td>
                        <td>{{ stock.price }}</td>
                        <td><p-sparkline [data]="stock.history" [tooltip]="true" showMarkers="last" width="8rem" [ariaLabel]="stock.symbol + ' price'" /></td>
                        <td><p-sparkline [data]="stock.change" type="bar" width="8rem" [ariaLabel]="stock.symbol + ' daily change'" /></td>
                    </tr>
                </ng-template>
            </p-table>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule, TableModule]
})
export class SparklineTableDemo {
    stocks: Stock[] = Array.from({ length: 100 }, (_, row) => {
        let seed = row + 1;
        const random = () => {
            seed = (seed * 16807) % 2147483647;

            return seed / 2147483647;
        };
        let price = 50 + random() * 150;
        const history: number[] = [];

        for (let day = 0; day < 30; day++) {
            price = Math.max(5, price + (random() - 0.48) * 6);
            history.push(Math.round(price * 100) / 100);
        }

        return {
            symbol: 'EX' + String(row + 1).padStart(3, '0'),
            price: history[history.length - 1],
            history,
            change: history.slice(-10).map((value, i, values) => (i ? Math.round((value - values[i - 1]) * 100) / 100 : 0))
        };
    });
}
```

## KPI Card

In a KPI card, a full width area chart gives the figure its history. showMarkers set to last points at the current value and the tooltip shows any other one on hover.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';

interface Kpi {
    title: string;
    value: string;
    trend: string;
    data: number[];
}

@Component({
    template: `
        <div class="card">
            <ul class="list-none m-0 p-0 grid gap-4" style="grid-template-columns: repeat(auto-fill, minmax(13rem, 1fr))">
                @for (kpi of kpis; track kpi.title) {
                    <li class="flex flex-col gap-2 p-4 rounded-border border border-surface-200 dark:border-surface-700">
                        <span class="text-surface-600 dark:text-surface-300">{{ kpi.title }}</span>
                        <span class="text-2xl font-semibold">{{ kpi.value }}</span>
                        <span class="text-sm">{{ kpi.trend }}</span>
                        <p-sparkline [data]="kpi.data" type="area" curve="smooth" showMarkers="last" [tooltip]="true" width="100%" height="3rem" [ariaLabel]="kpi.title" />
                    </li>
                }
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineKpiDemo {
    kpis: Kpi[] = [
        { title: 'Revenue', value: '$48,200', trend: '+12% this month', data: [31, 34, 33, 38, 36, 41, 40, 44, 43, 48] },
        { title: 'Active users', value: '12,940', trend: '+4% this month', data: [11.2, 11.8, 11.5, 12.1, 12.4, 12.2, 12.6, 12.9] },
        { title: 'Churn', value: '2.1%', trend: '-0.6 points this month', data: [3.1, 2.9, 3.0, 2.7, 2.6, 2.4, 2.3, 2.1] }
    ];
}
```

## Markers and Reference Line

showMarkers puts a dot on some points of a line or an area: last , minmax for the lowest and the highest values, in their own colors, or all . The dots keep their size and stay round whatever the width and the height of the chart. referenceLine draws a dashed line at a value, a goal for example, or at a statistic of the data: average , median , min or max . The scale includes it, so it stays in view. In a bullet chart it is the target.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';

@Component({
    template: `
        <div class="card">
            <ul class="list-none m-0 p-0 grid gap-4" style="grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr))">
                <li class="flex items-center justify-between gap-4">
                    <span>Last value</span>
                    <p-sparkline [data]="data" showMarkers="last" width="9rem" height="2rem" ariaLabel="Last value" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Lowest and highest</span>
                    <p-sparkline [data]="data" showMarkers="minmax" width="9rem" height="2rem" ariaLabel="Lowest and highest" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>All points</span>
                    <p-sparkline [data]="data" showMarkers="all" width="9rem" height="2rem" ariaLabel="All points" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Average</span>
                    <p-sparkline [data]="data" referenceLine="average" width="9rem" height="2rem" ariaLabel="Average" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Goal of 20</span>
                    <p-sparkline [data]="data" type="bar" [referenceLine]="20" width="9rem" height="2rem" ariaLabel="Goal of 20" />
                </li>
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineMarkersDemo {
    data = [8, 12, 9, 15, 6, 11, 14, 17, 13, 16];
}
```

## Colors

The chart follows the theme: the line, the area and the positive bars use the sparkline.color design token, the primary color by default, and the negative bars and the losses sparkline.negative.color . color and negativeColor override them on one chart with any CSS color, design token variables included. strokeWidth sets the width of the line in pixels.

```typescript
import { Component } from '@angular/core';
import { SparklineModule } from '@exhaustive-ui/core/sparkline';

@Component({
    template: `
        <div class="card">
            <ul class="list-none m-0 p-0 grid gap-4" style="grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr))">
                <li class="flex items-center justify-between gap-4">
                    <span>Theme colors</span>
                    <p-sparkline [data]="profit" type="bar" width="9rem" height="2rem" ariaLabel="Theme colors" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Custom colors</span>
                    <p-sparkline [data]="profit" type="bar" color="var(--p-sky-600)" negativeColor="var(--p-orange-600)" width="9rem" height="2rem" ariaLabel="Custom colors" />
                </li>
                <li class="flex items-center justify-between gap-4">
                    <span>Thick green line</span>
                    <p-sparkline [data]="data" type="area" color="var(--p-green-600)" [strokeWidth]="2.5" width="9rem" height="2rem" ariaLabel="Thick green line" />
                </li>
            </ul>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineColorsDemo {
    data = [8, 12, 9, 15, 6, 11, 14, 17, 13, 16];

    profit = [4, -2, 6, 3, -5, 7, 2, -1, 5, 8];
}
```

## Tooltip and Keyboard

With tooltip , hovering or touching the chart shows the value of the nearest point, with its label when data holds {{ '{' }} value, label {{ '}' }} objects. valueFormatter formats the values, here as currency, and a template named tooltip replaces the content. With focusable , the chart is in the tab order: it shows the last point when it gets the focus, and the left and right arrow keys, Home and End move between the points, announced to screen readers. onPointChange emits the active point, here to show it in the heading.

```typescript
import { Component, signal } from '@angular/core';
import { SparklineDatum, SparklineModule, SparklinePointChangeEvent } from '@exhaustive-ui/core/sparkline';

@Component({
    template: `
        <div class="card flex flex-col items-center gap-4">
            <span id="sparkline-tooltip-title" class="font-medium">Monthly revenue: {{ active() ?? 'move over the chart' }}</span>
            <p-sparkline [data]="months" type="bar" [tooltip]="true" [focusable]="true" [valueFormatter]="currency" width="16rem" height="4rem" ariaLabel="Monthly revenue" (onPointChange)="onPointChange($event)" />
            <p-sparkline [data]="months" [tooltip]="true" [focusable]="true" [valueFormatter]="currency" width="16rem" height="3rem" ariaLabel="Monthly revenue, custom tooltip">
                <ng-template #tooltip let-point>
                    <strong>{{ point.label }}</strong> {{ point.formattedValue }}
                </ng-template>
            </p-sparkline>
        </div>
    `,
    standalone: true,
    imports: [SparklineModule]
})
export class SparklineTooltipDemo {
    months: SparklineDatum[] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].map((label, i) => ({ label, value: 18000 + Math.round(Math.sin(i / 2) * 4000) + i * 900 }));

    active = signal<string | null>(null);

    currency = (value: number) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 }).format(value);

    onPointChange(event: SparklinePointChangeEvent) {
        this.active.set(event.point ? `${event.point.label} ${event.point.formattedValue}` : null);
    }
}
```

## Accessibility

Screen Reader The SVG has the img role and a text summary of the data as accessible name, for example "12 values from 3 to 18, last 15, up 25% from first", "12 results, 8 wins, 4 losses" or "value 68, target 80". ariaLabel names the chart and comes first: "Revenue: 12 values from 3 to 18...". ariaLabelledBy refers to a visible title instead, and the summary becomes the description. summaryFormatter writes another summary from the statistics of the data, and every text can be translated through labels ; locale or valueFormatter format the numbers. With focusable , the chart is in the tab order and lists its keys in aria-keyshortcuts . Each point reached with the keyboard is announced by a polite live region, with its label, its value and its position, "Mar: 15, 3 of 12". The tooltip is hidden from assistive technologies, which get the same text from the live region. Without focusable , the chart is a plain image with its summary and adds no live region. The lines, bars and markers keep a 3:1 contrast with the background in the light and dark color schemes. Colors are never the only cue: negative bars are also below the zero line, losses below the middle.

## Sparkline

Sparkline is a word-sized chart drawn in SVG: a line, an area, bars, wins and losses or a bullet chart, for table cells, cards and KPIs.

### Props

| Name | Type | Default | Description |
|------|------|---------|-------------|
| dt | Object | undefined | Defines scoped design tokens of the component. |
| unstyled | boolean | undefined | Indicates whether the component should be rendered without styles. |
| pt | SparklinePassThrough | undefined | Used to pass attributes to DOM elements inside the component. |
| ptOptions | PassThroughOptions | undefined | Used to configure passthrough(pt) options of the component. |
| data | SparklineData | [] | Values to draw: numbers, or  `{ value, label }`  objects whose label is shown in the tooltip. A null value leaves a gap. |
| type | SparklineType | 'line' | Kind of chart:  `line` ,  `area` ,  `bar`  with negative values below the zero line,  `winloss` , or  `bullet` , the last value against the reference line as target. |
| min | number | - | Lowest value of the scale. Defaults to the smallest value, 0 for bars and bullet charts. |
| max | number | - | Highest value of the scale. Defaults to the largest value, the reference line and the ranges included. |
| width | string \| number | '6em' | Width of the chart: a CSS length, or a number of pixels. The chart stretches to any width. |
| height | string \| number | '1.5em' | Height of the chart: a CSS length, or a number of pixels. |
| strokeWidth | number | - | Width of the line, in pixels. Defaults to the  `sparkline.line.width`  design token. |
| curve | SparklineCurve | 'linear' | Shape of the line: straight segments, or a smooth monotone curve that never overshoots the values. |
| showMarkers | SparklineMarkers | 'none' | Points of a line or an area marked with a dot: none, the last one, the lowest and the highest, or all of them. |
| referenceLine | SparklineReference | - | A dashed horizontal line at a value or at a statistic of the data:  `average` ,  `median` ,  `min`  or  `max` . In a bullet chart, the target. |
| ranges | number[] | - | Thresholds of the qualitative ranges of a bullet chart, for example  `[50, 75, 100]`  for poor, fair and good. Each band runs from the previous threshold. |
| color | string | - | Color of the line, the area and the positive bars, any CSS color. Defaults to the  `sparkline.color`  design token. |
| negativeColor | string | - | Color of the negative bars and the losses, any CSS color. Defaults to the  `sparkline.negative.color`  design token. |
| tooltip | boolean | false | Whether hovering or touching the chart shows the value of the nearest point in a tooltip, and the focused chart the value of the active point. |
| focusable | boolean | false | Whether the chart is in the tab order. The arrow keys, Home and End then move between the points, which are announced to screen readers. |
| ariaLabel | string | - | Name of the chart, for example the metric. The summary of the values follows it in the accessible name: "Revenue: 12 values from 3 to 18, last 15, up 25% from first". |
| ariaLabelledBy | string | - | Id of the element that labels the chart. The summary of the values is then its description. |
| summaryFormatter | (summary: SparklineSummary) => string | - | Replaces the summary of the values in the accessible name. It receives the statistics of the data and the default summary as  `text` . |
| valueFormatter | (value: number) => string | - | Formats the values of the tooltip, the announcements and the summary. Defaults to the locale's number format with up to two decimals. |
| locale | string | - | Locale of the default number format. Defaults to the application's  `LOCALE_ID` . |
| labels | Partial<SparklineLabels> | - | Texts of the component. Missing keys keep their default. |

### Emits

| Name | Parameters | Description |
|------|------------|-------------|
| onPointChange | event: SparklinePointChangeEvent | Callback to invoke when the active point changes, on hover or with the keyboard, when the tooltip is enabled or the chart is focusable. |

### Templates

| Name | Type | Description |
|------|------|-------------|
| tooltip | TemplateRef<SparklineTooltipTemplateContext> | Custom content of the tooltip. |

## Pass Through Options

| Name | Type | Description |
|------|------|-------------|
| host | PassThroughOption<HTMLElement, I> | Used to pass attributes to the host's DOM element. |
| root | PassThroughOption<HTMLElement, I> | Used to pass attributes to the root's DOM element, the host. |
| svg | PassThroughOption<SVGElement, I> | Used to pass attributes to the SVG element, with the img role and the summary as accessible name. |
| range | PassThroughOption<SVGRectElement, I> | Used to pass attributes to the qualitative range bands of a bullet chart. |
| area | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the area under the line. |
| line | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the line. |
| bars | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the path of the positive bars, the wins of a win-loss chart or the value bar of a bullet chart. |
| negativeBars | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the path of the negative bars or the losses of a win-loss chart. |
| baseline | PassThroughOption<SVGLineElement, I> | Used to pass attributes to the zero line of bar and win-loss charts. |
| referenceLine | PassThroughOption<SVGLineElement, I> | Used to pass attributes to the reference line, or the target of a bullet chart. |
| marker | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the markers. |
| activeMarker | PassThroughOption<SVGPathElement, I> | Used to pass attributes to the highlight of the active point. |
| tooltip | PassThroughOption<HTMLDivElement, I> | Used to pass attributes to the tooltip's DOM element. |
| liveRegion | PassThroughOption<HTMLSpanElement, I> | Used to pass attributes to the live region that announces the active point. |

## Theming

### CSS Classes

| Class | Description |
|-------|-------------|
| p-sparkline | Class name of the root element |
| p-sparkline-svg | Class name of the SVG element |
| p-sparkline-range | Class name of the qualitative range bands of a bullet chart |
| p-sparkline-area | Class name of the area |
| p-sparkline-line | Class name of the line |
| p-sparkline-bars | Class name of the positive bars |
| p-sparkline-bars-negative | Class name of the negative bars |
| p-sparkline-baseline | Class name of the zero line |
| p-sparkline-reference-line | Class name of the reference line |
| p-sparkline-marker | Class name of the markers |
| p-sparkline-active-marker | Class name of the active point |
| p-sparkline-active-bar | Class name of the active bar |
| p-sparkline-tooltip | Class name of the tooltip |

### Design Tokens

| Token | CSS Variable | Description |
|-------|--------------|-------------|
| sparkline.color | --p-sparkline-color | Color of the line, the area and the positive bars of root |
| sparkline.negative.color | --p-sparkline-negative-color | Color of the negative bars and the losses of root |
| sparkline.padding | --p-sparkline-padding | Padding of root |
| sparkline.border.radius | --p-sparkline-border-radius | Border radius of root |
| sparkline.focus.ring.width | --p-sparkline-focus-ring-width | Width of focus ring |
| sparkline.focus.ring.style | --p-sparkline-focus-ring-style | Style of focus ring |
| sparkline.focus.ring.color | --p-sparkline-focus-ring-color | Color of focus ring |
| sparkline.focus.ring.offset | --p-sparkline-focus-ring-offset | Offset of focus ring |
| sparkline.focus.ring.shadow | --p-sparkline-focus-ring-shadow | Shadow of focus ring |
| sparkline.line.width | --p-sparkline-line-width | Width of line |
| sparkline.area.opacity | --p-sparkline-area-opacity | Opacity of area |
| sparkline.bar.inactive.opacity | --p-sparkline-bar-inactive-opacity | Opacity of the other bars while one is active, of bar |
| sparkline.baseline.color | --p-sparkline-baseline-color | Color of baseline |
| sparkline.reference.line.color | --p-sparkline-reference-line-color | Color of reference line |
| sparkline.reference.line.width | --p-sparkline-reference-line-width | Width of reference line |
| sparkline.target.color | --p-sparkline-target-color | Color of target |
| sparkline.target.width | --p-sparkline-target-width | Width of target |
| sparkline.range.first.background | --p-sparkline-range-first-background | Background of the first band of range |
| sparkline.range.second.background | --p-sparkline-range-second-background | Background of the second band of range |
| sparkline.range.third.background | --p-sparkline-range-third-background | Background of the third band of range |
| sparkline.marker.color | --p-sparkline-marker-color | Color of marker |
| sparkline.marker.size | --p-sparkline-marker-size | Size of marker |
| sparkline.marker.min.color | --p-sparkline-marker-min-color | Color of the lowest value of marker |
| sparkline.marker.max.color | --p-sparkline-marker-max-color | Color of the highest value of marker |
| sparkline.active.marker.size | --p-sparkline-active-marker-size | Size of active marker |
| sparkline.tooltip.background | --p-sparkline-tooltip-background | Background of tooltip |
| sparkline.tooltip.color | --p-sparkline-tooltip-color | Color of tooltip |
| sparkline.tooltip.padding | --p-sparkline-tooltip-padding | Padding of tooltip |
| sparkline.tooltip.border.radius | --p-sparkline-tooltip-border-radius | Border radius of tooltip |
| sparkline.tooltip.shadow | --p-sparkline-tooltip-shadow | Shadow of tooltip |
| sparkline.tooltip.font.size | --p-sparkline-tooltip-font-size | Font size of tooltip |
| sparkline.tooltip.max.width | --p-sparkline-tooltip-max-width | Max width of tooltip |
| sparkline.tooltip.gutter | --p-sparkline-tooltip-gutter | Gutter of tooltip |

