
Syncfusion Angular Sparkline
- 166 installs
- Updated August 4, 2026
- syncfusion/angular-ui-components-skills
Use syncfusion-angular-sparkline for development tasks
About
syncfusion-angular-sparkline: A skill for development. This provides functionality for development workflows.
- syncfusion-angular-sparkline
Syncfusion Angular Sparkline by the numbers
- 166 all-time installs (skills.sh)
- +11 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #2,333 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/angular-ui-components-skills --skill syncfusion-angular-sparklineAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 166 |
|---|---|
| Last updated | August 4, 2026 |
| Repository | syncfusion/angular-ui-components-skills ↗ |
What it does
Use syncfusion-angular-sparkline for development tasks
Files
Implementing Syncfusion Angular Sparkline Component
When to Use This Skill
Use this skill when you need to:
- Visualize compact data - Display small time-series datasets inline within tables, grids, or dashboards
- Add sparkline charts - Render Line, Column, Area, Pie, or Win-Loss sparklines
- Enhance data presentation - Add markers for key points (high, low, start, end, negative)
- Display metrics inline - Show data labels and tooltips within sparklines
- Customize appearance - Apply themes, styling, accessibility features, or range bands
- Integrate into existing apps - Set up the Sparkline module with proper service injection
- Migrate from legacy - Move from EJ1 Sparkline to EJ2 Angular Sparkline
Component Overview
The Syncfusion Angular Sparkline is a lightweight data visualization component that displays compact charts in a small space. Sparklines are ideal for:
- Trend indicators within tables or dashboards
- Visual representation of sequential data
- Inline metrics showing performance or changes over time
Key characteristics:
- Compact rendering - Fits within grid cells or inline metrics
- Multiple types - Line, Column, Area, Pie, Win-Loss visualizations
- Interactive features - Tooltips, markers, data labels
- Customizable - Markers, colors, axis settings, themes
- Accessible - WCAG support, keyboard navigation, RTL support
⚠️ CRITICAL: Multiple Sparklines Require Unique IDs
>
When using more than one sparkline component on the same page, you MUST provide a unique id attribute to each sparkline to ensure proper rendering.>
```html
<!-- ✓ CORRECT - Unique IDs for multiple sparklines -->
<ejs-sparkline id="sparkline1" [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline id="sparkline2" [dataSource]="data2"></ejs-sparkline>
<ejs-sparkline id="sparkline3" [dataSource]="data3"></ejs-sparkline>
>
<!-- ✗ WRONG - No IDs or duplicate IDs causes rendering issues -->
<ejs-sparkline [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline [dataSource]="data2"></ejs-sparkline>
```
>
Without unique IDs, sparklines may:
- Not render at all
- Render with incorrect data
- Overlap or conflict with each other
- Display inconsistent styles
Documentation and Navigation Guide
This skill guides you through implementing sparklines. Here are the key topics:
Getting Started
📄 Read: references/getting-started.md
- Installation and package setup for Angular 19+
- Basic sparkline component implementation
- Module injection for SparklineTooltipService
- Data binding with dataSource, xName, and yName
- Enabling tooltips and running the application
- When to read: Before implementing your first sparkline
Sparkline Types
📄 Read: references/sparkline-types.md
- Line type (default, line chart visualization)
- Column type (vertical bar representation)
- Area type (filled area charts)
- Pie type (proportional/compositional data)
- Win-Loss type (binary outcomes: success/failure)
- Type comparison and selection criteria
- When to read: Choose which sparkline type best represents your data
Markers
📄 Read: references/markers.md
- Enabling markers for all points or specific points
- Marker options: All, Start, End, High, Low, Negative
- Customizing marker appearance (fill, border, size, opacity)
- Combining multiple marker types
- When to read: Highlight key data points (peaks, valleys, start/end)
Data Labels
📄 Read: references/data-labels.md
- Enabling data labels for specific points
- Label options: All, Start, End, High, Low, Negative
- Customizing label styling (fill, border, text color)
- Formatting label text with custom formats
- Displaying x and y values in labels
- When to read: Add numeric or formatted values directly on the sparkline
Advanced Features
📄 Read: references/advanced-features.md
- Range band visualization (shaded background regions)
- Axis customization (min, max, interval settings)
- User interactions (tooltip configuration, event handling)
- Special points customization (high/low point colors)
- Container sizing and responsive dimensions
- RTL (Right-to-Left) support
- When to read: Implement complex features like range bands, axis control, or events
Appearance and Accessibility
📄 Read: references/appearance-and-accessibility.md
- CSS themes and theme switching
- Appearance customization with CSS classes
- Localization (locale-specific formatting)
- WCAG accessibility compliance
- Keyboard navigation support
- Responsive design for different screen sizes
- When to read: Style the sparkline, support multiple locales, or ensure accessibility
Migration Guide
📄 Read: references/migration-guide.md
- Migrating from EJ1 Sparkline to EJ2
- API property mapping and changes
- Breaking changes and deprecated features
- Finding equivalents for legacy functionality
- When to read: You're upgrading from an older Syncfusion version
Quick Start Example
Here's a minimal example to render a basic sparkline:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
selector: 'app-container',
template: `<ejs-sparkline
id='sparkline-container'
[dataSource]="data"
xName="x"
yName="y"
type="Line">
</ejs-sparkline>`
})
export class AppComponent {
data = [
{ x: 'Jan', y: 2 },
{ x: 'Feb', y: 6 },
{ x: 'Mar', y: 4 },
{ x: 'Apr', y: 8 },
{ x: 'May', y: 5 }
]
}Output: A simple line sparkline showing the trend across months.
Common Patterns
Pattern 1: Sparkline in a Table Cell
Embed a sparkline within a grid or table to show trends for each row:
<table>
<tr>
<td>Product A</td>
<td><ejs-sparkline [dataSource]="salesA" type="Column" height="50px" width="150px"></ejs-sparkline></td>
</tr>
<tr>
<td>Product B</td>
<td><ejs-sparkline [dataSource]="salesB" type="Column" height="50px" width="150px"></ejs-sparkline></td>
</tr>
</table>Pattern 2: Highlight Key Points with Markers
Show markers on high and low points to emphasize performance peaks:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
[markerSettings]="markerSettings">
</ejs-sparkline>`
})
export class HighlightComponent {
data = [10, 25, 15, 35, 20, 30]
markerSettings = {
visible: ['High', 'Low'],
fill: '#FF5733',
size: 8,
opacity: 1
}
}Pattern 3: Add Tooltip for Details
Enable tooltip to show exact values on hover with custom formatting:
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<ejs-sparkline
[dataSource]="data"
xName="month"
yName="sales"
[tooltipSettings]="tooltipSettings">
</ejs-sparkline>`
})
export class TooltipComponent {
data = [
{ month: 'Jan', sales: 10000 },
{ month: 'Feb', sales: 15000 }
]
tooltipSettings = {
visible: true,
format: '${month}: ${sales} units'
}
}Pattern 4: Range Bands for Thresholds
Display shaded regions to show acceptable performance ranges:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Area"
[rangeBandSettings]="rangeBandSettings">
</ejs-sparkline>`
})
export class RangeBandComponent {
data = [20, 30, 25, 35, 28, 32, 40]
rangeBandSettings = [
{ startRange: 25, endRange: 35, color: '#90EE90', opacity: 0.3 }, // Good range
{ startRange: 15, endRange: 25, color: '#FFD700', opacity: 0.3 } // Warning range
]
}Pattern 5: Event Handling
Handle sparkline events for user interactions:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
(pointRegionMouseClick)="onPointClick($event)"
(sparklineMouseClick)="onSparklineClick($event)">
</ejs-sparkline>`
})
export class EventComponent {
data = [10, 25, 15, 35, 20]
onPointClick(args: any) {
console.log('Point clicked:', args.pointIndex, args.value)
}
onSparklineClick(args: any) {
console.log('Sparkline clicked')
}
}Key Props
| Property | Type | Default | Purpose |
|---|---|---|---|
dataSource | Array | [] | Data array (primitives or objects) - binds data to sparkline |
xName | string | - | Object property name for X values (e.g., 'month', 'date') |
yName | string | - | Object property name for Y values (e.g., 'sales', 'count') |
type | string | 'Line' | Sparkline type: Line, Column, Area, Pie, WinLoss |
markerSettings | object | - | Configure marker display and style (High, Low, Start, End, Negative, All) with fill, border, size, opacity properties |
dataLabelSettings | object | - | Configure data label display with visible array, format string, fill color, border, textStyle, and edgeLabelMode |
tooltipSettings | object | - | Tooltip configuration (visible, format with ${x}/${y} tokens, fill, border, textStyle, trackLineSettings) |
height | string/number | '100px' | Container height in px (e.g., '150px') or percentage (e.g., '100%') |
width | string/number | '100%' | Container width in px (e.g., '300px') or percentage (e.g., '100%') |
rangeBandSettings | object/array | - | Configure background shading regions (startRange, endRange, color, opacity) - supports single object or array for multiple bands |
axisSettings | object | - | Axis configuration (minX, maxX, minY, maxY, intervalX, intervalY, valueType: Numeric/Category/DateTime) |
highPointColor | string | - | Color for highest point in data series (hex or named color) |
lowPointColor | string | - | Color for lowest point in data series (hex or named color) |
startPointColor | string | - | Color for first/start point in the series |
endPointColor | string | - | Color for last/end point in the series |
negativePointColor | string | - | Color for negative data values (below zero) |
fill | string | - | Fill color for the sparkline area/column/bars (primary series color) |
lineWidth | number | 1 | Thickness of line type sparkline (1-10 range recommended) |
opacity | number | 1 | Opacity of the sparkline series (0-1 range) |
enableRtl | boolean | false | Enable Right-to-Left layout for RTL languages (Arabic, Hebrew) |
valueType | string | 'Numeric' | Data type for axis values: Numeric, Category, DateTime |
format | string | - | Number format for axis values (e.g., 'n2' for 2 decimals, 'c' for currency) |
useGroupingSeparator | boolean | false | Enable thousand separator formatting (e.g., 1,000) |
theme | string | 'Material' | Visual theme: Material, Fabric, Bootstrap, HighContrast, etc. |
border | object | - | Border configuration (color, width) for sparkline container |
containerArea | object | - | Container customization (background color, border settings) |
padding | object | - | Padding for sparkline (left, right, top, bottom in pixels) |
Common Use Cases
1. Dashboard Metrics - Display mini charts showing KPI trends in real-time dashboards and metrics views. Ideal for executive dashboards with multiple metrics displayed in a compact grid layout.
2. Financial Data Visualization - Visualize stock prices, trading volumes, or currency trends with range bands for support/resistance zones. Use markers to highlight significant price points and tooltips for detailed values.
3. Performance Monitoring - Show system metrics (CPU, memory, disk usage, network throughput) monitored over 24-hour periods. Color-code negative spikes and use range bands to show acceptable operating ranges.
4. Data Table Integration - Embed sparklines within data grid cells to compare performance trends across multiple products, users, or regions in table rows. Each row shows its own mini trend visualization.
5. Win-Loss Analysis - Track success/failure outcomes (pass/fail, approved/rejected, win/loss) in a compact binary format using the WinLoss type. Perfect for game results, test outcomes, or approval workflows.
6. Time Series Condensed View - Display historical data in a condensed format with trend visualization. Show weekly, monthly, or yearly patterns without taking up significant screen space.
7. Sales Pipeline Tracking - Show monthly/quarterly sales trends by product category or sales territory. Use different sparkline types to represent different metrics (revenue as Area, units as Column).
8. User Activity Analytics - Track engagement metrics (page visits, active users, session duration) over specific time periods. Identify patterns and anomalies with marker highlighting.
9. Quality Metrics Dashboard - Display defect rates, uptime percentages, or quality scores across production batches. Use range bands to show acceptable quality zones and markers to flag outliers.
10. Resource Utilization Monitoring - Monitor bandwidth consumption, storage capacity trends, or license usage patterns at a glance. Set axis bounds to show capacity limits and use color-coded points for threshold breaches.
11. IoT Sensor Data - Display real-time sensor readings (temperature, humidity, pressure) in compact charts within IoT monitoring dashboards. Show 24-hour trends for each sensor in minimal space.
12. Social Media Analytics - Track follower growth, engagement rates, or post reach over time. Use Pie sparklines to show proportional engagement across different platforms.
---
Next Steps: Start with getting-started.md to install and render your first sparkline, then explore other reference guides based on your needs.
API Reference
A concise API reference for the Syncfusion Angular Sparkline is available in the references folder. It includes property anchors, method links, and event argument types mapped to the official docs.
Read the API reference: references/api-reference.md
Advanced Features in Sparklines
Table of Contents
- Working with Multiple Sparklines
- Unique ID Requirement
- Dynamic Sparkline Generation
- Range Band
- Basic Range Band
- Multiple Range Bands
- Range Band Properties
- Use Cases
- Axis Customization
- Setting Axis Min and Max
- Custom Interval
- Axis Properties Reference
- Real Example: Percentage Data
- User Interactions
- Tooltip Configuration
- Tooltip Properties
- Special Points Customization
- Highlight High and Low Points
- Negative Point Color
- Properties
- Container Sizing
- Fixed Size
- Percentage Size
- Dynamic Sizing
- RTL Support
- RTL Behavior
- Real-World Examples
- Server Performance Monitoring
- Stock Price with Zones
- Network Throughput Dashboard
- Combined Features Example
- Performance Optimization
Working with Multiple Sparklines
Unique ID Requirement
When displaying multiple sparkline components on the same page, you MUST assign a unique id attribute to each sparkline. Without unique IDs, sparklines may fail to render or display incorrect data.
Why This Matters:
- Each sparkline creates DOM elements with ID-based references
- Duplicate or missing IDs cause rendering conflicts
- The component uses the ID to manage its internal state and SVG elements
Example: Multiple Sparklines with Unique IDs
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
template: `
<div class="dashboard">
<!-- Sales Trend -->
<ejs-sparkline
id="sales-sparkline"
[dataSource]="salesData"
type="Line"
fill="#0066CC"
height="80px">
</ejs-sparkline>
<!-- Revenue Trend -->
<ejs-sparkline
id="revenue-sparkline"
[dataSource]="revenueData"
type="Column"
fill="#4CAF50"
height="80px">
</ejs-sparkline>
<!-- User Growth -->
<ejs-sparkline
id="users-sparkline"
[dataSource]="usersData"
type="Area"
fill="#FF9800"
height="80px">
</ejs-sparkline>
</div>
`
})
export class DashboardComponent {
salesData = [10, 25, 15, 30, 20, 35];
revenueData = [100, 120, 110, 150, 130, 170];
usersData = [50, 75, 60, 90, 80, 110];
}Common Mistakes:
<!-- ✗ WRONG - No IDs -->
<ejs-sparkline [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline [dataSource]="data2"></ejs-sparkline>
<!-- ✗ WRONG - Duplicate IDs -->
<ejs-sparkline id="sparkline" [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline id="sparkline" [dataSource]="data2"></ejs-sparkline>
<!-- ✓ CORRECT - Unique IDs -->
<ejs-sparkline id="sparkline-1" [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline id="sparkline-2" [dataSource]="data2"></ejs-sparkline>Dynamic Sparkline Generation
When generating sparklines dynamically with *ngFor, use unique identifiers from your data:
@Component({
template: `
<div class="metrics-grid">
<div *ngFor="let metric of metrics" class="metric-card">
<h4>{{ metric.name }}</h4>
<ejs-sparkline
[id]="'sparkline-' + metric.id"
[dataSource]="metric.values"
[type]="metric.type"
[fill]="metric.color"
height="60px">
</ejs-sparkline>
</div>
</div>
`
})
export class MetricsDashboard {
metrics = [
{
id: 'sales',
name: 'Sales',
values: [10, 25, 15, 30],
type: 'Line',
color: '#0066CC'
},
{
id: 'revenue',
name: 'Revenue',
values: [100, 120, 110, 150],
type: 'Column',
color: '#4CAF50'
},
{
id: 'users',
name: 'Users',
values: [50, 75, 60, 90],
type: 'Area',
color: '#FF9800'
}
];
}ID Naming Best Practices:
- Use descriptive names:
"sales-trend","revenue-chart","user-growth" - Use consistent prefixes:
"sparkline-{purpose}","chart-{metric}" - For dynamic generation:
"sparkline-" + uniqueIdentifier - Avoid special characters; stick to alphanumeric and hyphens
Range Band
Range bands display shaded background regions to highlight data ranges or thresholds.
Basic Range Band
Add a shaded region showing a normal operating range:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="data"
type="Area"
[rangeBandSettings]="{
start: 20,
end: 30,
color: '#E3F2FD',
opacity: 0.4
}">
</ejs-sparkline>`
})
export class RangeBandComponent {
data = [10, 25, 15, 35, 28, 22, 40]
}Output: A light blue shaded region from Y=20 to Y=30, showing the acceptable range.
Multiple Range Bands
Highlight multiple ranges (e.g., good, warning, danger):
@Component({
template: `<ejs-sparkline id='container' width='150px' height='150px' lineWidth= 2 fill = '#0d3c9b' [rangeBandSettings] = 'rangeBandSettings' [dataSource]="data">
</ejs-sparkline>`
})
export class MultiRangeBandComponent {
public data: object[] = [ 0, 6, 4, 1, 3, 2, 5 ] as any;
public rangeBandSettings: object[] = [{
startRange: 1,
endRange: 3,
color: '#bfd4fc',
opacity:0.4
}];
}Range Band Properties
| Property | Type | Purpose |
|---|---|---|
start | number | Starting Y value for the range |
end | number | Ending Y value for the range |
color | string | Background color (hex or named) |
opacity | number | Transparency (0-1) |
Use Cases
- SLA Monitoring - Show acceptable vs. breach ranges
- Performance Metrics - Display normal operating zones
- Temperature Control - Highlight ideal temperature bands
- Quality Assurance - Mark acceptable product ranges
Axis Customization
Customize the axis bounds and interval for better data representation.
Setting Axis Min and Max
Control the data range displayed:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[axisSettings]="{
minX: 0,
maxX: 10,
minY: 0,
maxY: 100,
valueType: 'Numeric'
}">
</ejs-sparkline>`
})
export class AxisRangeComponent {
data = [20, 50, 30, 80, 60]
}Effect: The Y-axis scales from 0 to 100 (not auto-fitted to data).
Custom Interval
Set the Y-axis interval for specific tick spacing:
axisSettings = {
minY: 0,
maxY: 100,
intervalY: 25 // Intervals at 0, 25, 50, 75, 100
}Axis Properties Reference
| Property | Type | Purpose |
|---|---|---|
minX | number | Minimum X-axis value |
maxX | number | Maximum X-axis value |
minY | number | Minimum Y-axis value |
maxY | number | Maximum Y-axis value |
intervalX | number | X-axis interval spacing |
intervalY | number | Y-axis interval spacing |
valueType | string | Data type: 'Numeric', 'Category', 'DateTime' |
Real Example: Percentage Data
@Component({
template: `<ejs-sparkline
[dataSource]="conversionRates"
xName="week"
yName="percentage"
type="Line"
[axisSettings]="{
minY: 0,
maxY: 100
}">
</ejs-sparkline>`
})
export class ConversionComponent {
conversionRates = [
{ week: 'W1', percentage: 45 },
{ week: 'W2', percentage: 58 },
{ week: 'W3', percentage: 62 }
]
}User Interactions
Tooltip Configuration
Customize tooltip appearance and behavior:
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<ejs-sparkline
[dataSource]="data"
[tooltipSettings]="{
visible: true,
fill: '#1A1A1A',
border: { color: '#FFA500' }
}">
</ejs-sparkline>`
})
export class TooltipConfigComponent {
data = [10, 25, 15, 30, 20]
}Tooltip Properties
| Property | Type | Purpose |
|---|---|---|
visible | boolean | Enable/disable tooltip |
format | string | Format string with ${x}, ${y} |
fill | string | Background color |
border.color | string | Border color |
opacity | number | Transparency |
textStyle.color | string | Text color |
Special Points Customization
Customize colors for high, low, and negative points:
Highlight High and Low Points
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[highPointColor]="'#00B050'"
[lowPointColor]="'#FF0000'">
</ejs-sparkline>`
})
export class SpecialPointsComponent {
data = [20, 50, 30, 80, 60, 15, 75]
}Output: Highest column (80) is green, lowest (15) is red.
Negative Point Color
Color negative values differently:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
[negativePointColor]="'#FF5733'">
</ejs-sparkline>`
})
export class NegativePointComponent {
data = [10, -5, 15, -3, 8, 12]
}Properties
| Property | Type | Purpose |
|---|---|---|
highPointColor | string | Color for highest point |
lowPointColor | string | Color for lowest point |
negativePointColor | string | Color for negative values |
startPointColor | string | Color for first point |
endPointColor | string | Color for last point |
Container Sizing
Fixed Size
Set explicit dimensions:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
height="100px"
width="300px">
</ejs-sparkline>`
})
export class FixedSizeComponent {
data = [2, 6, 4, 8, 5]
}Percentage Size
Use percentage for responsive sizing:
@Component({
template: `<div style="width: 500px;">
<ejs-sparkline
[dataSource]="data"
height="100px"
width="100%">
</ejs-sparkline>
</div>`
})
export class ResponsiveSizeComponent {
data = [2, 6, 4, 8, 5]
}Dynamic Sizing
Adjust size based on data:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
[height]="getHeight()"
[width]="getWidth()">
</ejs-sparkline>`
})
export class DynamicSizeComponent {
data = [2, 6, 4, 8, 5]
getHeight(): string {
return this.data.length > 10 ? '150px' : '100px'
}
getWidth(): string {
return this.data.length * 20 + 'px'
}
}RTL Support
Enable Right-to-Left layout for RTL languages (Arabic, Hebrew, etc.):
@Component({
template: `<div dir="rtl">
<ejs-sparkline
[dataSource]="data"
type="Column"
[enableRtl]="true">
</ejs-sparkline>
</div>`
})
export class RTLComponent {
data = [10, 25, 15, 30, 20]
}RTL Behavior
- X-axis labels appear right-aligned
- Animation flows from right to left
- Tooltips position appropriately for RTL space
Real-World Examples
Server Performance Monitoring
@Component({
imports: [SparklineModule],
standalone: true,
template: `<div>
<h4>CPU Usage Last 24h</h4>
<ejs-sparkline id='container' width='150px' height='150px' lineWidth= 2 fill = '#0d3c9b' [rangeBandSettings] = 'rangeBandSettings' [dataSource]="cpuUsage" xName='hour' yName='percent'>
</ejs-sparkline>
</div>`
})
export class ServerMonitorComponent {
cpuUsage = [
{ hour: 0, percent: 35 },
{ hour: 1, percent: 42 },
{ hour: 2, percent: 88 }, // Peak
{ hour: 3, percent: 45 }
]
public rangeBandSettings: object[] = [{
startRange: 35,
endRange: 67,
color: 'green',
opacity:0.4
}];
}Stock Price with Zones
@Component({
template: `<ejs-sparkline
[dataSource]="stockPrice"
xName="day"
yName="price"
type="Line"
valueType='Category'
[dataLabelSettings]="{ visible: ['Start', 'End'] }"
[rangeBandSettings]="[
{ startRange: 100, endRange: 110, color: '#4CAF50', opacity: 0.1 },
{ startRange: 130, endRange: 140, color: '#F44336', opacity: 0.1 }
]">
</ejs-sparkline>`
})
export class StockPriceComponent {
stockPrice = [
{ day: 'Mon', price: 105 },
{ day: 'Tue', price: 115 },
{ day: 'Wed', price: 135 },
{ day: 'Thu', price: 128 }
]
}Network Throughput Dashboard
@Component({
template: `<div>
<ejs-sparkline
[dataSource]="throughput"
type="Column"
height="120px"
[axisSettings]="{ maxY: 1000 }"
[highPointColor]="'#4CAF50'"
[tooltipSettings]="{
visible: true
}">
</ejs-sparkline>
</div>`
})
export class NetworkComponent {
throughput = [
150, 280, 320, 450, 390, 520, 480, 600
]
}Combined Features Example
Complete example with multiple advanced features:
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<ejs-sparkline
[dataSource]="monthlyMetrics"
xName="month"
yName="value"
type="Area"
valueType="Category"
height="150px"
width="100%"
[axisSettings]="{ minY: 0, maxY: 100 }"
[rangeBandSettings]="{ start: 70, end: 100, color: '#90EE90', opacity: 0.3 }"
[markerSettings]="{ visible: ['High', 'Low'], size: 8 }"
[dataLabelSettings]="{ visible: ['High', 'Low'] }"
[tooltipSettings]="{ visible: true, format: '${x}: ${y}%' }"
[highPointColor]="'#4CAF50'"
[lowPointColor]="'#FF5252'">
</ejs-sparkline>`
})
export class CompleteExampleComponent {
monthlyMetrics = [
{ month: 'Jan', value: 65 },
{ month: 'Feb', value: 75 },
{ month: 'Mar', value: 80 },
{ month: 'Apr', value: 85 },
{ month: 'May', value: 82 },
{ month: 'Jun', value: 90 }
]
}Features Combined:
- ✓ Area visualization
- ✓ Range band highlighting success zone
- ✓ Markers on extremes
- ✓ Data labels
- ✓ Custom tooltips
- ✓ Special point colors
- ✓ Responsive width
Performance Optimization
For sparklines with advanced features and large datasets:
1. Avoid 'All' markers/labels - Use specific types 2. Limit range bands - 2-3 bands maximum 3. Use Column type - Renders faster with 1000+ points 4. Simplify tooltips - Short format strings 5. Debounce updates - When binding to streams
// ✓ Good for performance
[markerSettings]="{ visible: ['High', 'Low'] }"
[dataLabelSettings]="{ visible: ['End'] }"
// ✗ Poor for 1000+ points
[markerSettings]="{ visible: ['All'] }"
[dataLabelSettings]="{ visible: ['All'] }"Responsive Design
Mobile-Optimized Sparklines
Create responsive sparklines that adapt to different screen sizes:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { CommonModule } from '@angular/common'
import { Component } from '@angular/core'
@Component({
imports: [SparklineModule, CommonModule],
standalone: true,
template: `<div class="sparkline-container">
<div class="sparkline-item">
<h5>Revenue</h5>
<ejs-sparkline
[dataSource]="revenueData"
xName="month"
yName="revenue"
type="Area"
[height]="getMobileHeight()"
[width]="getMobileWidth()">
</ejs-sparkline>
</div>
</div>`,
styles: [`
.sparkline-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
padding: 20px;
}
.sparkline-item {
padding: 15px;
border: 1px solid #e0e0e0;
border-radius: 4px;
}
@media (max-width: 768px) {
.sparkline-container {
grid-template-columns: 1fr;
}
}
`]
})
export class ResponsiveSparklineComponent {
revenueData = [
{ month: 'Jan', revenue: 45000 },
{ month: 'Feb', revenue: 52000 },
{ month: 'Mar', revenue: 48000 },
{ month: 'Apr', revenue: 65000 },
{ month: 'May', revenue: 72000 },
{ month: 'Jun', revenue: 68000 }
]
getMobileHeight(): string {
if (window.innerWidth < 768) {
return '80px'
}
return '120px'
}
getMobileWidth(): string {
if (window.innerWidth < 768) {
return '100%'
}
return '100%'
}
}Accessibility and Screen Reader Support
WCAG 2.1 Compliance
Ensure sparklines are accessible to users with disabilities:
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
import { CommonModule } from '@angular/common'
import { Component } from '@angular/core'
@Component({
imports: [SparklineModule, CommonModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<div role="region" [attr.aria-label]="'Sales trend chart showing quarterly data'">
<h3>Quarterly Sales Trend</h3>
<ejs-sparkline
[dataSource]="salesData"
xName="quarter"
yName="sales"
type="Line"
[tooltipSettings]="{
visible: true,
format: '\${quarter}: \${sales} units'
}"
role="img"
[attr.aria-label]="'Line chart displaying quarterly sales from Q1 to Q4'">
</ejs-sparkline>
<div role="region" [attr.aria-label]="'Sales data table'" class="data-table">
<table>
<caption>Quarterly Sales Data</caption>
<thead>
<tr>
<th>Quarter</th>
<th>Sales (Units)</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of salesData">
<td>{{ item.quarter }}</td>
<td>{{ item.sales }}</td>
</tr>
</tbody>
</table>
</div>
</div>`,
styles: [`
.data-table {
margin-top: 20px;
border: 1px solid #ccc;
padding: 10px;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f5f5f5;
font-weight: bold;
}
`]
})
export class AccessibleSparklineComponent {
salesData = [
{ quarter: 'Q1', sales: 25000 },
{ quarter: 'Q2', sales: 35000 },
{ quarter: 'Q3', sales: 32000 },
{ quarter: 'Q4', sales: 48000 }
]
}Event Handling
Sparklines support various events to handle user interactions and lifecycle changes.
Available Events
| Event | Trigger | Use Case |
|---|---|---|
loaded | After sparkline finishes rendering | Initialize custom logic, logging |
sparklineMouseClick | User clicks anywhere on sparkline | Navigate to details page |
sparklineMouseMove | Mouse moves over sparkline | Custom tooltip behavior |
pointRegionMouseClick | User clicks specific data point | Show detailed metrics |
pointRegionMouseMove | Mouse moves over data point | Highlight related data |
resize | Sparkline container resizes | Recalculate dimensions |
Point Click Event
Handle clicks on individual data points:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core'
@Component({
imports: [SparklineModule],
standalone: true,
template: `<div>
<ejs-sparkline
[dataSource]="salesData"
xName="month"
yName="sales"
type="Column"
(pointRegionMouseClick)="onPointClick($event)">
</ejs-sparkline>
<div *ngIf="selectedPoint">
<h4>Details for {{ selectedPoint.x }}</h4>
<p>Sales: {{ selectedPoint.y }}</p>
</div>
</div>`
})
export class PointClickComponent {
salesData = [
{ month: 'Jan', sales: 10000 },
{ month: 'Feb', sales: 15000 },
{ month: 'Mar', sales: 12000 },
{ month: 'Apr', sales: 18000 }
]
selectedPoint: any = null
onPointClick(args: any) {
this.selectedPoint = {
x: args.pointIndex,
y: args.value
}
console.log('Point clicked:', args.pointIndex, args.value)
}
}Sparkline Click Event
Handle clicks on the entire sparkline:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
(sparklineMouseClick)="onSparklineClick($event)">
</ejs-sparkline>`
})
export class SparklineClickComponent {
data = [10, 25, 15, 35, 20, 30]
onSparklineClick(args: any) {
console.log('Sparkline clicked')
// Navigate to detailed chart view
// this.router.navigate(['/details'])
}
}Loaded Event
Execute logic after sparkline finishes rendering:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Area"
(loaded)="onLoaded($event)">
</ejs-sparkline>`
})
export class LoadedEventComponent {
data = [10, 25, 15, 35, 20]
onLoaded(args: any) {
console.log('Sparkline loaded successfully')
// Add custom SVG elements or annotations
// Track analytics
}
}Mouse Move Event
Track mouse movement for custom interactions:
@Component({
template: `<div>
<ejs-sparkline
[dataSource]="data"
type="Line"
(pointRegionMouseMove)="onMouseMove($event)">
</ejs-sparkline>
<div class="hover-info">
Hovering over point: {{ hoveredIndex }}
</div>
</div>`
})
export class MouseMoveComponent {
data = [10, 25, 15, 35, 20, 30]
hoveredIndex: number = -1
onMouseMove(args: any) {
this.hoveredIndex = args.pointIndex
}
}Resize Event
Handle sparkline container resize:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[height]="height"
[width]="width"
(resize)="onResize($event)">
</ejs-sparkline>`
})
export class ResizeComponent {
data = [10, 25, 15, 35, 20]
height = '100px'
width = '100%'
onResize(args: any) {
console.log('Sparkline resized:', args.currentSize)
// Adjust marker sizes or label fonts based on new dimensions
}
}Combined Event Handling
Use multiple events together:
@Component({
imports: [SparklineModule, CommonModule],
standalone: true,
template: `<div class="event-demo">
<ejs-sparkline
[dataSource]="performanceData"
xName="hour"
yName="cpu"
type="Line"
[markerSettings]="{ visible: ['High', 'Low'] }"
(loaded)="onLoaded($event)"
(pointRegionMouseClick)="onPointClick($event)"
(sparklineMouseClick)="onSparklineClick($event)">
</ejs-sparkline>
<div class="event-log">
<h4>Event Log:</h4>
<ul>
<li *ngFor="let event of eventLog">{{ event }}</li>
</ul>
</div>
</div>`
})
export class CombinedEventsComponent {
performanceData = [
{ hour: 0, cpu: 35 },
{ hour: 1, cpu: 42 },
{ hour: 2, cpu: 88 },
{ hour: 3, cpu: 45 }
]
eventLog: string[] = []
onLoaded(args: any) {
this.logEvent('Sparkline loaded')
}
onPointClick(args: any) {
this.logEvent(`Point ${args.pointIndex} clicked: ${args.value}%`)
}
onSparklineClick(args: any) {
this.logEvent('Sparkline container clicked')
}
logEvent(message: string) {
this.eventLog.unshift(`[${new Date().toLocaleTimeString()}] ${message}`)
if (this.eventLog.length > 10) {
this.eventLog.pop()
}
}
}Print and Export
Export sparklines to image formats for reports and documentation.
Export to Image
Export sparkline as PNG, JPEG, or SVG:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component, ViewChild } from '@angular/core'
import { SparklineComponent } from '@syncfusion/ej2-angular-charts'
@Component({
imports: [SparklineModule],
standalone: true,
template: `<div>
<ejs-sparkline
#sparkline
[dataSource]="data"
type="Line">
</ejs-sparkline>
<button (click)="exportPNG()">Export as PNG</button>
<button (click)="exportJPEG()">Export as JPEG</button>
<button (click)="exportSVG()">Export as SVG</button>
</div>`
})
export class ExportComponent {
@ViewChild('sparkline') sparkline!: SparklineComponent
data = [10, 25, 15, 35, 20, 30]
exportPNG() {
this.sparkline.export('PNG', 'Sparkline')
}
exportJPEG() {
this.sparkline.export('JPEG', 'Sparkline')
}
exportSVG() {
this.sparkline.export('SVG', 'Sparkline')
}
}Print Sparkline
Print the sparkline directly:
@Component({
template: `<div>
<ejs-sparkline
#sparkline
[dataSource]="data"
type="Area">
</ejs-sparkline>
<button (click)="printSparkline()">Print</button>
</div>`
})
export class PrintComponent {
@ViewChild('sparkline') sparkline!: SparklineComponent
data = [10, 25, 15, 35, 20, 30]
printSparkline() {
this.sparkline.print()
}
}Best Practices Summary
| Practice | Benefit | Example |
|---|---|---|
| Use appropriate type | Better data representation | Pie for composition, WinLoss for binary |
| Limit markers/labels | Improved readability | High/Low only, not All |
| Apply range bands | Context and thresholds | Green/yellow/red zones |
| Enable tooltips | User understanding | Hover for exact values |
| Responsive sizing | Mobile compatibility | 60px mobile, 100px desktop |
| Semantic colors | Accessibility | High contrast ratios (4.5:1+) |
| Lazy loading | Performance at scale | Page 6 datasets per page |
| Include data table | Screen reader support | WCAG 2.1 AA compliant |
Sparkline API Reference (Syncfusion Angular)
This file summarizes selected properties, methods, and events for the Sparkline component and links to official API anchors for complex models and event argument types.
Official docs
- Index: https://ej2.syncfusion.com/angular/documentation/api/sparkline/index-default
Component import
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts';Tag
<ejs-sparkline>
Selected Properties (with links)
dataSource: Object[] | DataManager— Data for the sparkline.type?: [SparklineType](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinetype)—Line | Column | Area | Pie | WinLoss.xName?: string— Field name for X values.yName?: string— Field name for Y values.valueType?: [SparklineValueType](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinevaluetype)—Numeric | DateTime.height?: string— Height of the container.width?: string— Width of the container.fill?: string— Series fill color (default#00bdae).lineWidth?: number— Line width for line type (default1).markerSettings?: [SparklineMarkerSettingsModel](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinemarkersettingsmodel)— Marker configuration.dataLabelSettings?: [SparklineDataLabelSettingsModel](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinedatalabelsettingsmodel)— Data label configuration.tooltipSettings?: [SparklineTooltipSettingsModel](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinetooltipsettingsmodel)— Tooltip config.rangeBandSettings?: [RangeBandSettingsModel[]](https://ej2.syncfusion.com/angular/documentation/api/sparkline/rangebandsettingsmodel)— Range bands.axisSettings?: [AxisSettingsModel](https://ej2.syncfusion.com/angular/documentation/api/sparkline/axissettingsmodel)— Axis customization.palette?: string[]— Palette for column and pie types.useGroupingSeparator?: boolean— Enable group separators.format?: string— Internationalization format.theme?: [SparklineTheme](https://ej2.syncfusion.com/angular/documentation/api/sparkline/sparklinetheme)— Theme.enableRtl?: boolean— RTL support.enablePersistence?: boolean— Persist component state.
For full property list and defaults, see the official API index.
Methods
destroy(): void— Destroy the component. (see: https://ej2.syncfusion.com/angular/documentation/api/sparkline/index-default#destroy)getModuleName(): string— Get component name. (see: https://ej2.syncfusion.com/angular/documentation/api/sparkline/index-default#getmodulename)renderSparkline(): void— Render sparkline elements. (see: https://ej2.syncfusion.com/angular/documentation/api/sparkline/index-default#rendersparkline)
Events (selected)
load— ISparklineLoadEventArgsloaded— ISparklineLoadedEventArgsaxisRendering— IAxisRenderingEventArgsmarkerRendering— IMarkerRenderingEventArgsdataLabelRendering— IDataLabelRenderingEventArgspointRendering— ISparklinePointEventArgspointRegionMouseClick— IPointRegionEventArgspointRegionMouseMove— IPointRegionEventArgssparklineMouseClick— ISparklineMouseEventArgssparklineMouseMove— ISparklineMouseEventArgstooltipInitialize— ITooltipRenderingEventArgsresize— ISparklineResizeEventArgs
Example (Angular standalone)
import { Component } from '@angular/core';
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts';
@Component({
imports: [SparklineModule],
providers: [SparklineTooltipService],
standalone: true,
template: `\
<ejs-sparkline [dataSource]="data" xName="x" yName="y" type="Line" [tooltipSettings]="{ visible: true }">\
</ejs-sparkline>`
})
export class ExampleComponent {
public data = [ { x: 'Jan', y: 2 }, { x: 'Feb', y: 6 } ];
}---
If you'd like, I can expand this with full signatures/defaults or add these inline anchors into the other reference pages (advanced-features.md, etc.).
Appearance and Accessibility
Table of Contents
- CSS Themes and Styling
- Built-in Themes
- Importing Themes in Angular
- Customizing Sparkline Appearance
- Changing Colors Dynamically
- CSS Classes for Styling
- Responsive Design
- Localization
- Changing Locale
- Supported Locales
- Custom Locale Strings
- Dark Mode Support
- Implementing Dark Theme
- CSS Variables for Themes
- Real-World Examples
- Dashboard with Theme Switching
- Testing for Accessibility
- Chrome DevTools Audit
- Screen Reader Testing
- Keyboard Navigation Testing
- Best Practices
CSS Themes and Styling
Built-in Themes
Syncfusion provides multiple predefined themes. Include the theme CSS in your application:
<!-- In index.html or main.ts -->
<!-- Material Theme (Default) -->
<link rel="stylesheet" href="node_modules/@syncfusion/ej2-base/styles/material.css">
<!-- Bootstrap Theme -->
<link rel="stylesheet" href="node_modules/@syncfusion/ej2-base/styles/bootstrap.css">
<!-- Bootstrap 5 Theme -->
<link rel="stylesheet" href="node_modules/@syncfusion/ej2-base/styles/bootstrap5.css">
<!-- Tailwind CSS Theme -->
<link rel="stylesheet" href="node_modules/@syncfusion/ej2-base/styles/tailwind.css">
<!-- Fluent Theme -->
<link rel="stylesheet" href="node_modules/@syncfusion/ej2-base/styles/fluent.css">Importing Themes in Angular
Import theme CSS in styles.css:
/* styles.css */
@import '../node_modules/@syncfusion/ej2-base/styles/material.css';Or in angular.json:
{
"styles": [
"node_modules/@syncfusion/ej2-base/styles/material.css",
"src/styles.css"
]
}Customizing Sparkline Appearance
Changing Colors Dynamically
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[fill]="'#FF6B6B'"
[border]="{ color: '#C92A2A', width: 2 }">
</ejs-sparkline>`
})
export class ColoredSparklineComponent {
data = [10, 25, 15, 30, 20]
}CSS Classes for Styling
Add custom CSS classes to style sparklines:
@Component({
template: `<ejs-sparkline
id="sparkline-1"
[dataSource]="data"
type="Area"
class="custom-sparkline">
</ejs-sparkline>`
})
export class CustomStyleComponent {
data = [10, 25, 15, 30, 20]
}/* styles.css */
.custom-sparkline {
background-color: #F5F5F5;
border: 1px solid #DDD;
border-radius: 4px;
padding: 8px;
}
#sparkline-1 svg {
filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}Responsive Design
Make sparklines adapt to different screen sizes:
@Component({
template: `<div class="sparkline-container">
<ejs-sparkline
[dataSource]="data"
[height]="containerHeight"
[width]="containerWidth">
</ejs-sparkline>
</div>`
})
export class ResponsiveSparklineComponent {
data = [10, 25, 15, 30, 20]
containerHeight = '100px'
containerWidth = '100%'
constructor() {
this.updateSizeForScreen()
window.addEventListener('resize', () => this.updateSizeForScreen())
}
updateSizeForScreen() {
const width = window.innerWidth
if (width < 768) {
this.containerHeight = '80px'
} else if (width < 1024) {
this.containerHeight = '100px'
} else {
this.containerHeight = '120px'
}
}
}Localization
Changing Locale
Configure locale-specific formatting:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
import { setLocale } from '@syncfusion/ej2-base'
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
xName="date"
yName="value"
valueType="Category"
[dataSource]="data"
[locale]="'fr-FR'">
</ejs-sparkline>`
})
export class LocalizedSparklineComponent {
data = [
{ date: 'Jan', value: 100 },
{ date: 'Fev', value: 150 },
{ date: 'Mar', value: 120 }
]
}Supported Locales
en-US- English (US)en-GB- English (GB)de-DE- Germanfr-FR- Frenches-ES- Spanishja-JP- Japanesezh-CN- Chinese (Simplified)ar-SA- Arabiche-IL- Hebrew
Custom Locale Strings
Create custom locale definitions:
import { L10n } from '@syncfusion/ej2-base'
L10n.load({
'custom-locale': {
'sparkline': {
'tooltip': 'Valeur: ${y}',
'label': '${x}: ${y}'
}
}
})Dark Mode Support
Implementing Dark Theme
@Component({
selector: 'app-root',
template: `<div [ngClass]="{ dark: isDarkMode }">
<button (click)="toggleDarkMode()">Toggle Theme</button>
<ejs-sparkline
[dataSource]="data"
[fill]="isDarkMode ? '#BB86FC' : '#6200EE'">
</ejs-sparkline>
</div>`,
styles: [`
:host.dark {
background-color: #121212;
color: #FFFFFF;
}
:host.dark ::ng-deep .e-sparkline {
background-color: #1E1E1E;
}
`]
})
export class DarkModeComponent {
isDarkMode = false
data = [10, 25, 15, 30, 20]
toggleDarkMode() {
this.isDarkMode = !this.isDarkMode
}
}CSS Variables for Themes
Use CSS custom properties for theme switching:
:root {
--sparkline-fill: #6200EE;
--sparkline-bg: #FFFFFF;
--sparkline-text: #000000;
}
[data-theme="dark"] {
--sparkline-fill: #BB86FC;
--sparkline-bg: #121212;
--sparkline-text: #FFFFFF;
}
.custom-sparkline {
background-color: var(--sparkline-bg);
color: var(--sparkline-text);
}Real-World Examples
Dashboard with Theme Switching
@Component({
imports: [SparklineModule, CommonModule],
standalone: true,
template: `<div class="dashboard" [ngClass]="{ dark: isDarkMode }">
<div class="theme-toggle">
<button (click)="toggleTheme()">
{{ isDarkMode ? '☀️ Light' : '🌙 Dark' }}
</button>
</div>
<div class="metrics">
<div class="metric-card">
<h3>Users</h3>
<ejs-sparkline
[dataSource]="userData"
type="Column"
[fill]="sparklineFill"
height="100px">
</ejs-sparkline>
</div>
</div>
</div>`,
styles: [`
.dashboard {
background: white;
color: #000;
transition: 0.3s;
}
.dashboard.dark {
background: #1E1E1E;
color: white;
}
.metric-card {
border: 1px solid #DDD;
padding: 16px;
margin: 8px;
border-radius: 8px;
}
.dashboard.dark .metric-card {
border-color: #444;
}
`]
})
export class DashboardComponent {
isDarkMode = false
revenueData = [5000, 7500, 6200, 8100, 7500]
userData = [100, 150, 130, 180, 160]
get sparklineFill(): string {
return this.isDarkMode ? '#BB86FC' : '#6200EE'
}
toggleTheme() {
this.isDarkMode = !this.isDarkMode
}
}Testing for Accessibility
Chrome DevTools Audit
1. Open Chrome DevTools → Lighthouse 2. Run accessibility audit 3. Check for:
- Color contrast
- ARIA labels
- Keyboard navigation
- Screen reader compatibility
Screen Reader Testing
Test with popular screen readers:
- NVDA (Windows)
- JAWS (Windows)
- VoiceOver (macOS)
- TalkBack (Android)
Keyboard Navigation Testing
Verify:
- [ ] Sparkline can be focused (Tab key)
- [ ] Tooltip appears on focus (if enabled)
- [ ] All interactive elements are keyboard accessible
- [ ] No keyboard traps
Best Practices
1. Always include tooltips for data visualization accessibility 2. Use ARIA labels to describe chart purpose 3. Provide data tables as fallback for screen readers 4. Maintain color contrast (WCAG AA minimum 4.5:1 for text) 5. Support keyboard navigation for all interactive elements 6. Test with real assistive technology before deployment 7. Use semantic HTML with proper role attributes 8. Include focus indicators for keyboard users
Data Labels in Sparklines
Data labels display numeric values directly on or near the sparkline, improving readability without requiring tooltips.
Table of Contents
- Enabling Data Labels
- Display Labels on All Points
- Display Labels on Specific Points
- Label Display Options
- Customizing Label Appearance
- Basic Styling
- Advanced Customization
- Label Properties Reference
- Formatting Label Text
- Default Label Behavior
- Custom Format with X and Y Values
- Format String Examples
- Conditional Formatting
- Real-World Examples
- Sales Dashboard
- KPI Tracking
- Financial Data
- Combining Labels with Markers
- Label Positioning
- Edge Cases and Troubleshooting
- Issue: Labels Overlapping
- Issue: Labels Cut Off
- Issue: Format Not Applied
- Issue: Labels Don't Display on Negative Values
- Performance Considerations
Enabling Data Labels
Display Labels on All Points
Show a label for every data point:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
id='sparkline-container'
[dataSource]="data"
type="Column"
[dataLabelSettings]="{ visible: ['All'] }"
height="120px"
width="250px">
</ejs-sparkline>`
})
export class AppComponent {
data = [2, 6, 4, 8, 5, 1, 7]
}Output: Each column displays its numeric value.
Display Labels on Specific Points
Show labels only for important data points:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
[dataLabelSettings]="{
visible: ['Start', 'End', 'High', 'Low']
}">
</ejs-sparkline>`
})
export class SpecificLabelsComponent {
data = [10, 25, 15, 30, 20]
}Output: Labels appear only on start, end, highest, and lowest values.
Label Display Options
Available label options:
| Option | Purpose |
|---|---|
All | Label all data points |
Start | Label first point |
End | Label last point |
High | Label highest value |
Low | Label lowest value |
Negative | Label negative values (financial data) |
// Show multiple label types
[dataLabelSettings]="{
visible: ['High', 'Low', 'Negative']
}"Customizing Label Appearance
Basic Styling
Change label colors and styling:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[dataLabelSettings]="{
visible: ['All'],
fill: '#1E88E5', // Label background color
border: { color: '#0D47A1' } // Border color
}">
</ejs-sparkline>`
})
export class StyledLabelsComponent {
data = [50, 100, 75, 150, 120]
}Advanced Customization
Customize text style, opacity, and border:
dataLabelSettings = {
visible: ['High', 'Low'],
fill: '#FFF9E6',
opacity: 0.9,
border: {
color: '#FF6F00',
width: 2
},
textStyle: {
color: '#1A1A1A',
fontFamily: 'Arial',
fontSize: '12px',
fontWeight: 'bold'
}
}Label Properties Reference
| Property | Type | Default | Purpose |
|---|---|---|---|
visible | Array | [] | Which points to label |
fill | string | '#FFFFFF' | Background color |
opacity | number | 1 | Transparency (0-1) |
border.color | string | - | Border color |
border.width | number | 0 | Border thickness |
textStyle.color | string | '#000000' | Text color |
textStyle.fontSize | string | '12px' | Font size |
textStyle.fontFamily | string | 'Segoe UI' | Font name |
textStyle.fontWeight | string | 'normal' | Font weight (bold, normal) |
Formatting Label Text
Default Label Behavior
By default, labels display only the Y value:
[dataLabelSettings]="{ visible: ['All'] }"
// Displays: "10", "25", "15", "30", "20"Custom Format with X and Y Values
Display both X-axis label and Y value:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
xName="month"
yName="sales"
valueType="Category"
type="Column"
[dataLabelSettings]="dataLabelSettings">
</ejs-sparkline>`
})
export class FormattedLabelsComponent {
data = [
{ month: 'Jan', sales: 50 },
{ month: 'Feb', sales: 100 },
{ month: 'Mar', sales: 75 }
]
dataLabelSettings = {
visible: ['All'],
format: '${month}: ${sales}k'
}
}Output: Labels show "Jan: 50k", "Feb: 100k", "Mar: 75k"
Format String Examples
// Display Y value with currency
format: '${y}'
// Display X and Y with units
format: '${x}: ${y}%'
// Display Y value rounded
format: '${y:.1f}' // Single decimal place
// Display X label only
format: '${x}'
// Custom text with values
format: 'Sales: ${y}K in ${x}'Conditional Formatting
Format labels based on values (high/low colors):
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[dataLabelSettings]="labelSettings">
</ejs-sparkline>`
})
export class ConditionalLabelsComponent {
data = [10, 50, 30, 100, 20]
labelSettings = {
visible: ['All']
}
}Real-World Examples
Sales Dashboard
Display sales figures with labels on high/low points:
@Component({
imports: [SparklineModule],
standalone: true,
template: `<div>
<h3>Monthly Sales Trend</h3>
<ejs-sparkline
[dataSource]="monthlySales"
xName="month"
yName="amount"
valueType="Category"
type="Column"
[dataLabelSettings]="{
visible: ['High', 'Low'],
fill: '#FFF',
border: { color: '#FF6F00' }
}"
[markerSettings]="{
visible: ['High', 'Low'],
fill: '#FF6F00'
}">
</ejs-sparkline>
</div>`
})
export class SalesDashboardComponent {
monthlySales = [
{ month: 'Jan', amount: 5000 },
{ month: 'Feb', amount: 7500 },
{ month: 'Mar', amount: 4200 },
{ month: 'Apr', amount: 9800 }, // High
{ month: 'May', amount: 3500 } // Low
]
}KPI Tracking
Show labeled values for quick metric reading:
@Component({
template: `<div class="metrics">
<ejs-sparkline
[dataSource]="cpuUsage"
[dataLabelSettings]="{
visible: ['End'],
textStyle: { fontSize: '14px', fontWeight: 'bold' }
}"
type="Area">
</ejs-sparkline>
</div>`
})
export class KPITrackerComponent {
cpuUsage = [20, 35, 45, 52, 58, 65, 72]
}Financial Data
Display formatted currency with data labels:
@Component({
template: `<ejs-sparkline
[dataSource]="quarterlyProfit"
xName="quarter"
yName="profit"
type="Line"
[dataLabelSettings]="{
visible: ['All'],
format: '${y}K',
fill: '#E8F5E9',
border: { color: '#4CAF50' }
}">
</ejs-sparkline>`
})
export class FinancialComponent {
quarterlyProfit = [
{ quarter: 'Q1', profit: 250 },
{ quarter: 'Q2', profit: 380 },
{ quarter: 'Q3', profit: 290 },
{ quarter: 'Q4', profit: 450 }
]
}Combining Labels with Markers
Use labels and markers together for clear data point emphasis:
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
[markerSettings]="{
visible: ['High', 'Low'],
fill: '#E74C3C',
size: 8
}"
[dataLabelSettings]="{
visible: ['High', 'Low'],
fill: '#FFF',
border: { color: '#E74C3C' }
}">
</ejs-sparkline>`
})
export class MarkerAndLabelComponent {
data = [10, 25, 15, 35, 20]
}Output: High and low points display both markers and numeric labels.
Label Positioning
Labels automatically position above or beside sparkline elements. For sparkline types:
- Line/Area - Labels appear above the line
- Column - Labels appear on top of columns
- Pie - Labels appear on pie slices
- WinLoss - Labels appear above bars
Edge Cases and Troubleshooting
Issue: Labels Overlapping
Cause: Too many labels on a small sparkline or large font size.
Solution: 1. Use specific label types instead of 'All':
[dataLabelSettings]="{ visible: ['High', 'Low'] }"2. Reduce font size:
textStyle: { fontSize: '10px' }3. Increase sparkline dimensions:
height="150px"
width="300px"Issue: Labels Cut Off
Cause: Insufficient container space.
Solution: Add padding to the sparkline container or increase its height:
<div style="padding: 20px; height: 200px;">
<ejs-sparkline [dataSource]="data"></ejs-sparkline>
</div>Issue: Format Not Applied
Cause: Format string syntax error or xName/yName not defined.
Solution: Verify correct syntax:
// ✓ Correct
format: '${x}: ${y}k'
// ✗ Wrong
format: '{x}: {y}k' // Missing $And ensure data properties are mapped:
xName="month" // Must match object property name
yName="value" // Must match object property nameIssue: Labels Don't Display on Negative Values
Cause: Using 'Negative' without negative data.
Solution: Ensure data contains negative values:
// ✓ Has negatives
data = [10, -5, 15, -3, 8]
// ✗ No negatives
data = [10, 5, 15, 3, 8]Performance Considerations
- 'All' labels - Slower with dense data (500+ points)
- Specific labels - Better performance; use 'High', 'Low', 'Start', 'End'
- Format strings - Simple formats are faster
- Large fonts - Can impact rendering on mobile devices
For sparklines with 1000+ points, limit labels to essential points (High, Low, Start, End).
Getting Started with Angular Sparkline
Table of Contents
- Prerequisites
- Installation
- Step 1: Add Syncfusion Package
- Step 2: Verify Installation
- Basic Implementation
- Minimal Sparkline Component
- Adding Minimal Data
- Module Injection
- Enabling Tooltip Service
- Data Binding
- Using Primitive Arrays
- Using Object Arrays
- Example: Sales Data by Category
- Enabling Tooltips
- Basic Tooltip Setup
- Customizing Tooltip Format
- Running Your Application
- Development Server
- Verifying Sparkline Renders
- Build for Production
- Troubleshooting
- Issue: SparklineModule not Found
- Issue: Sparkline Renders Empty
- Issue: Multiple Sparklines Not Rendering
- Issue: Tooltip Doesn't Appear
- Issue: Data Not Updating
- Issue: Performance Issues with Large Data
Prerequisites
Before implementing the Sparkline component, ensure:
- Angular 19+ is installed (the examples use standalone components)
- npm is available on your system
- You have a working Angular project (or create one with
ng new my-app) - Zone.js is available in your project (typically installed with Angular CLI)
Note: If using Angular 15-18, the examples work with minimal adjustments. For Angular 14 and below, consider upgrading or refer to legacy documentation.
Installation
Step 1: Add Syncfusion Package
Install the Syncfusion Angular Charts package (which includes Sparkline):
ng add @syncfusion/ej2-angular-chartsThis command will:
- Add
@syncfusion/ej2-angular-chartsto yourpackage.json - Install peer dependencies automatically
- Register necessary providers if using older Angular versions
Step 2: Verify Installation
Check that package.json includes:
{
"dependencies": {
"@syncfusion/ej2-angular-charts": "^latest",
"@angular/core": "^19.0.0"
}
}If not, manually add the package:
npm install @syncfusion/ej2-angular-chartsBasic Implementation
Minimal Sparkline Component
Create a component with a basic sparkline:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
selector: 'app-container',
template: `<ejs-sparkline
id='sparkline-container'
height="100px"
width="100%">
</ejs-sparkline>`
})
export class AppComponent { }Output: An empty SVG element (no data yet). You'll add data in the next step.
⚠️ IMPORTANT: Unique IDs Required for Multiple Sparklines
>
If you plan to display more than one sparkline component on the same page, you MUST provide a unique id attribute to each sparkline. Without unique IDs, sparklines may not render properly or may conflict with each other.>
Example: Multiple Sparklines with Unique IDs
```html
<!-- ✓ CORRECT - Each sparkline has a unique ID -->
<ejs-sparkline id="sparkline-sales" [dataSource]="salesData"></ejs-sparkline>
<ejs-sparkline id="sparkline-revenue" [dataSource]="revenueData"></ejs-sparkline>
<ejs-sparkline id="sparkline-users" [dataSource]="usersData"></ejs-sparkline>
>
<!-- ✗ WRONG - No IDs causes rendering issues -->
<ejs-sparkline [dataSource]="salesData"></ejs-sparkline>
<ejs-sparkline [dataSource]="revenueData"></ejs-sparkline>
>
<!-- ✗ WRONG - Duplicate IDs causes conflicts -->
<ejs-sparkline id="chart" [dataSource]="salesData"></ejs-sparkline>
<ejs-sparkline id="chart" [dataSource]="revenueData"></ejs-sparkline>
```
>
Symptoms of Missing Unique IDs:
- Sparklines don't render at all
- Only the first sparkline displays correctly
- Data appears in wrong sparklines
- Tooltips or markers show incorrect data
- Console errors about duplicate DOM IDs
Adding Minimal Data
To render an actual sparkline, provide data:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="[2, 6, 4, 8, 5, 1, 7]"
type="Line"
height="100px">
</ejs-sparkline>`
})
export class AppComponent { }Output: A line sparkline with 7 data points.
Module Injection
Some features require injecting service providers. The most common is the SparklineTooltipService for tooltip support.
Enabling Tooltip Service
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService], // ← Inject tooltip service
template: `<ejs-sparkline
[dataSource]="data"
[tooltipSettings]="{ visible: true }">
</ejs-sparkline>`
})
export class AppComponent {
data = [2, 6, 4, 8, 5]
}Key Point: Without injecting SparklineTooltipService, the tooltip won't work even if you set visible: true.
Data Binding
Using Primitive Arrays
For simple numeric data:
dataSource = [10, 15, 8, 12, 20, 18]Use in template:
<ejs-sparkline [dataSource]="dataSource" type="Column"></ejs-sparkline>Using Object Arrays
For more complex data with multiple fields:
dataSource = [
{ month: 'Jan', sales: 2 },
{ month: 'Feb', sales: 6 },
{ month: 'Mar', sales: 4 },
{ month: 'Apr', sales: 8 },
{ month: 'May', sales: 5 }
]Map the fields:
<ejs-sparkline
[dataSource]="dataSource"
xName="month"
yName="sales"
type="Area">
</ejs-sparkline>Key Properties:
xName- The property name for X-axis values (often labels)yName- The property name for Y-axis values (numerical data)
Example: Sales Data by Category
@Component({
template: `
<ejs-sparkline
[dataSource]="products"
xName="month"
yName="revenue"
valueType="Category"
type="Line"
height="60px">
</ejs-sparkline>
`
})
export class DashboardComponent {
products = [
{ month: 'Jan', revenue: 1000 },
{ month: 'Feb', revenue: 1200 },
{ month: 'Mar', revenue: 1100 },
{ month: 'Jan', revenue: 800 },
{ month: 'Feb', revenue: 950 },
{ month: 'Mar', revenue: 1050 }
]
}Enabling Tooltips
Tooltips display data values on hover.
Basic Tooltip Setup
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<ejs-sparkline
[dataSource]="[2, 6, 4, 8, 5]"
[tooltipSettings]="{ visible: true }"
type="Line">
</ejs-sparkline>`
})
export class AppComponent { }Behavior: Hover over the sparkline to see tooltips.
Customizing Tooltip Format
tooltipSettings = {
visible: true,
format: '${x}: ${y}', // Display as "Month: Value"
fill: '#FF5733' // Tooltip background color
}Use in template:
<ejs-sparkline
[dataSource]="data"
[tooltipSettings]="tooltipSettings">
</ejs-sparkline>Running Your Application
Development Server
Start the Angular development server:
npm startor
ng serveOpen your browser and navigate to http://localhost:4200.
Verifying Sparkline Renders
Check the browser console for errors. The sparkline should appear as:
- A compact line, column, or area chart depending on the type
- An interactive visualization when hovering (if tooltip is enabled)
Build for Production
ng build --configuration productionThe output will be in the dist/ folder, ready to deploy.
Troubleshooting
Issue: SparklineModule not Found
Solution: Ensure the import path is correct:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
// ↓ correct package nameIssue: Sparkline Renders Empty
Cause: No data provided or incorrect data mapping.
Solution: 1. Provide dataSource with values 2. For objects, ensure xName and yName match property names:
dataSource = [{ label: 'Jan', value: 10 }]
xName="label" // ← matches 'label' property
yName="value" // ← matches 'value' propertyIssue: Multiple Sparklines Not Rendering
Cause: Missing or duplicate id attributes when using multiple sparkline components on the same page.
Symptoms:
- Only the first sparkline displays correctly
- Some sparklines don't render at all
- Data appears in the wrong sparkline
- Tooltips show incorrect values
- Browser console shows duplicate ID warnings
Solution: Provide a unique `id` attribute to each sparkline component:
<!-- ✓ CORRECT - Unique IDs -->
<ejs-sparkline id="sparkline-1" [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline id="sparkline-2" [dataSource]="data2"></ejs-sparkline>
<ejs-sparkline id="sparkline-3" [dataSource]="data3"></ejs-sparkline>
<!-- ✗ WRONG - No IDs -->
<ejs-sparkline [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline [dataSource]="data2"></ejs-sparkline>
<!-- ✗ WRONG - Duplicate IDs -->
<ejs-sparkline id="chart" [dataSource]="data1"></ejs-sparkline>
<ejs-sparkline id="chart" [dataSource]="data2"></ejs-sparkline>TypeScript Example with Multiple Sparklines:
@Component({
template: `
<div class="sparkline-container">
<ejs-sparkline id="sales-sparkline" [dataSource]="salesData"></ejs-sparkline>
<ejs-sparkline id="revenue-sparkline" [dataSource]="revenueData"></ejs-sparkline>
<ejs-sparkline id="users-sparkline" [dataSource]="usersData"></ejs-sparkline>
</div>
`
})
export class AppComponent {
salesData = [10, 25, 15, 30, 20];
revenueData = [100, 120, 110, 150, 130];
usersData = [50, 75, 60, 90, 80];
}Best Practices:
- Use descriptive IDs that identify the sparkline's purpose (e.g.,
"sales-trend","revenue-chart") - Use a consistent naming convention (e.g.,
"sparkline-{name}") - For dynamically generated sparklines, use unique identifiers from your data:
<ejs-sparkline
*ngFor="let item of items"
[id]="'sparkline-' + item.id"
[dataSource]="item.data">
</ejs-sparkline>Issue: Tooltip Doesn't Appear
Cause: Service not injected.
Solution:
import { SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
@Component({
providers: [SparklineTooltipService] // ← Required
})Issue: Data Not Updating
Cause: Data reference not changed after update.
Solution: Use Angular change detection by reassigning the array:
updateData() {
this.dataSource = [...this.dataSource, newValue] // Create new reference
}Issue: Performance Issues with Large Data
Solution:
- Use the
ColumnorAreatype instead ofLinefor large datasets - Reduce
heightandwidthto minimize render overhead - Consider virtualizing multiple sparklines (show only visible items)
Markers in Sparklines
Markers highlight important data points in a sparkline, making peaks, valleys, and specific values visually distinct.
Table of Contents
- Adding Markers to All Points
- Markers for Specific Points
- Start and End Points
- High and Low Points
- Negative Points
- Combining Multiple Marker Types
- Customizing Marker Appearance
- Basic Customization
- Advanced Customization
- Marker Properties
- Real-World Examples
- Sales Performance Tracking
- Network Uptime Monitoring
- Temperature Extremes
- Marker Interaction with Data Labels
- Troubleshooting
- Issue: Markers Not Appearing
- Issue: Markers Overlapping Data
- Issue: Custom Colors Not Applied
- Performance Tips
Adding Markers to All Points
To display markers for every data point:
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
selector: 'app-container',
template: `<ejs-sparkline
id='sparkline-container'
[dataSource]="data"
type="Line"
[markerSettings]="{ visible: ['All'] }"
height="100px"
width="200px">
</ejs-sparkline>`
})
export class AppComponent {
data = [2, 6, 4, 8, 5, 1, 7]
}Output: A marker (small dot) appears at each data point.
Markers for Specific Points
Highlight only important points to reduce visual clutter:
Start and End Points
Show markers only at the first and last data points:
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="data" >
</ejs-sparkline>`
})
export class StartEndMarkersComponent {
public data: object[] = [0, 6, 4, 1, 3, 2, 5] as any;
public markerSettings: object= {
visible: ['Start', 'End']
};
}Use Case: Quickly compare beginning and ending values.
High and Low Points
Emphasize the maximum and minimum values:
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="data" >
</ejs-sparkline>`
})
export class HighLowMarkersComponent {
public data: object[] = [0, 6, 4, 1, 3, 2, 5] as any;
public markerSettings: object= {
visible: ['High', 'Low']
};
}Output: Markers highlight the highest value (160) and lowest value (50).
Negative Points
Mark negative values (useful for financial data):
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px'[dataSource]="data" >
</ejs-sparkline>`
})
export class NegativeMarkersComponent {
public data: object[] = [10, 5, -8, 12, -3, 15, 8] // Negative values marked
}Use Case: Financial losses, error rates, or deficit months.
Combining Multiple Marker Types
Show multiple marker types simultaneously:
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="data" >
</ejs-sparkline>`
})
export class CombinedMarkersComponent {
public data: object[] = [0, 6, 4, 1, 3, 2, 5] as any;
public markerSettings: object= {
visible: ['High', 'Low', 'Negative', 'Start', 'End']
};
}Customizing Marker Appearance
Basic Customization
Change marker color, size, and border:
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="data" >
</ejs-sparkline>`
})
export class CustomMarkersComponent {
public data: object[] = [0, 6, 4, 1, 3, 2, 5] as any;
public markerSettings: object= {
visible: ['All'],
fill: '#FF5733',
border: { color: '#000' },
size: 8
};
}Output: Larger orange markers with black borders on all points.
Advanced Customization
Customize opacity and border width:
markerSettings = {
visible: ['High', 'Low'],
fill: '#4472C4',
size: 10,
opacity: 0.8,
border: {
color: '#1F497D',
width: 2
}
}Marker Properties
| Property | Type | Default | Purpose |
|---|---|---|---|
visible | Array | [] | Points to mark: All, Start, End, High, Low, Negative |
fill | string | '#4472C4' | Marker background color |
size | number | 4 | Marker diameter in pixels |
opacity | number | 1 | Transparency (0-1) |
border.color | string | - | Border color |
border.width | number | 0 | Border thickness |
Real-World Examples
Sales Performance Tracking
Highlight peaks and troughs in weekly sales:
@Component({
imports: [SparklineModule],
standalone: true,
template: `<div>
<p>Sales Trend (with high/low markers)</p>
<ejs-sparkline
[dataSource]="weeklySales"
xName="day"
yName="amount"
valueType="Category"
type="Column"
[markerSettings]="{
visible: ['High', 'Low'],
fill: '#E74C3C',
size: 8
}">
</ejs-sparkline>
</div>`
})
export class SalesTrackingComponent {
weeklySales = [
{ day: 'Mon', amount: 2000 },
{ day: 'Tue', amount: 2500 },
{ day: 'Wed', amount: 1800 },
{ day: 'Thu', amount: 3500 }, // High
{ day: 'Fri', amount: 1200 }, // Low
{ day: 'Sat', amount: 2800 }
]
}Network Uptime Monitoring
Mark when network goes down (negative):
@Component({
template: `<ejs-sparkline id='container' xName="hour"
yName="status"
type="Line"
valueType="Category"
type="Area" width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="hourlyTemp" >
</ejs-sparkline>`
})
export class UptimeMonitorComponent {
hourlyTemp = [
{ hour: 1, status: 1 },
{ hour: 2, status: 1 },
{ hour: 3, status: -1 }, // Downtime
{ hour: 4, status: 1 },
{ hour: 5, status: -1 }, // Downtime
{ hour: 6, status: 1 }
]
public markerSettings: object= {
visible: ['Negative'],
fill: '#E74C3C',
size: 10
};
}Temperature Extremes
Mark high and low temperatures throughout the day:
@Component({
template: `<ejs-sparkline id='container' xName="hour"
yName="celsius"
valueType="Category"
type="Area" width='350px' height='200px' [markerSettings] ='markerSettings' [dataSource]="hourlyTemp" >
</ejs-sparkline>`
})
export class TempMonitorComponent {
hourlyTemp = [
{ hour: '6am', celsius: 12 },
{ hour: '12pm', celsius: 28 }, // High
{ hour: '6pm', celsius: 20 },
{ hour: '12am', celsius: 8 } // Low
]
public markerSettings: object= {
visible: ['High', 'Low']
};
}Marker Interaction with Data Labels
You can combine markers with data labels for richer information:
@Component({
template: `<ejs-sparkline id='container' width='350px' height='200px' [dataLabelSettings] = 'dataLabelSettings' [markerSettings] ='markerSettings' [dataSource]="data" >
</ejs-sparkline>`
})
export class MarkersWithLabelsComponent {
public data: object[] = [0, 6, 4, 1, 3, 2, 5] as any;
public markerSettings: object= {
visible: ['High', 'Low']
};
public dataLabelSettings: object ={
visible: ['High', 'Low']
};
}Output: Each high/low point shows both a marker and its value label.
Troubleshooting
Issue: Markers Not Appearing
Cause: markerSettings object not provided or visible array is empty.
Solution:
// ✗ Wrong - visible is empty
[markerSettings]="{ visible: [] }"
// ✓ Correct
[markerSettings]="{ visible: ['All'] }"
// or
[markerSettings]="{ visible: ['High', 'Low'] }"Issue: Markers Overlapping Data
Cause: Markers are too large or too close together.
Solution: Reduce marker size or use specific marker types instead of 'All':
[markerSettings]="{
visible: ['High', 'Low'], // Only specific points
size: 5 // Smaller markers
}"Issue: Custom Colors Not Applied
Cause: Property names or syntax issues.
Solution: Verify correct property structure:
// ✓ Correct structure
[markerSettings]="{
fill: '#FF0000',
border: { color: '#000' }
}"Performance Tips
- Limit marker types - Use specific types ('High', 'Low') instead of 'All' for large datasets
- Reduce marker size - Larger markers may impact performance with dense data
- Line vs. Column - Column sparklines with markers render faster than lines with many points
- For 1000+ points, avoid 'All' markers; use 'High', 'Low', or 'Negative' instead
Migration Guide: EJ1 to EJ2 Angular Sparkline
This guide helps you migrate from the legacy EJ1 (Essential JS 1) Sparkline to the modern EJ2 Angular Sparkline component.
Table of Contents
- Key Differences
- Package and Setup Migration
- EJ1 Setup
- EJ2 Setup
- Component Declaration Migration
- EJ1 Approach
- EJ2 Approach
- API Property Migration
- Common Property Mappings
- Data Binding Migration
- Marker Configuration Migration
- EJ1 Marker Setup
- EJ2 Marker Setup
- Data Label Configuration Migration
- EJ1 Data Labels
- EJ2 Data Labels
- Tooltip Configuration Migration
- EJ1 Tooltips
- EJ2 Tooltips
- Event Migration
- EJ1 Events
- EJ2 Events
- Type System Migration
- EJ1 Type Names
- EJ2 Type Names
- Complete Migration Example
- EJ1 Implementation
- EJ2 Implementation
- Breaking Changes
- Removed Features
- Changed Default Values
- Service Migration
- EJ1 Services
- EJ2 Services
- Testing and Validation
- Test Checklist
- Performance Comparison
- Troubleshooting Migration Issues
- Issue: Sparkline Not Rendering
- Issue: Data Not Binding
- Issue: Old jQuery Code Breaking
- Resources
- Getting Help
Key Differences
| Aspect | EJ1 | EJ2 |
|---|---|---|
| Package | jquery.ej2.sparkline.js | @syncfusion/ej2-angular-charts |
| Framework | jQuery-based | Angular standalone/module |
| Data Binding | Direct array or URL | Strongly typed with mapping |
| Properties | CamelCase | CamelCase (same) |
| Events | jQuery events | Angular events |
| Build | Script tags | npm package, tree-shakeable |
Package and Setup Migration
EJ1 Setup
<!-- EJ1: Script tag approach -->
<script src="jquery.min.js"></script>
<script src="ej.web.all.min.js"></script>
<div id="sparkline"></div>
<script>
$("#sparkline").ejSparkline({
dataSource: [2, 6, 4, 8, 5],
type: "Line"
});
</script>EJ2 Setup
// EJ2: Angular component approach
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core'
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="[2, 6, 4, 8, 5]"
type="Line">
</ejs-sparkline>`
})
export class AppComponent { }Component Declaration Migration
EJ1 Approach
<!-- HTML initialization -->
<div id="sparkline" data-role="ejsparkline" data-type="Line"></div>
<script>
// jQuery selector approach
$("#sparkline").ejSparkline({
dataSource: chartData,
height: 100,
width: 200
});
</script>EJ2 Approach
// Component-based approach
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="chartData"
height="100px"
width="200px"
type="Line">
</ejs-sparkline>`
})
export class SparklineComponent {
chartData = [...]
}API Property Migration
Common Property Mappings
| EJ1 Property | EJ2 Property | Notes |
|---|---|---|
dataSource | dataSource | Same, but uses binding [dataSource] |
type | type | Line, Column, Area, Pie, WinLoss (WinLoss replaces ColumnWinLoss) |
xName | xName | Maps object field for X values |
yName | yName | Maps object field for Y values |
height | height | Use string units: "100px" |
width | width | Use string units: "200px" |
fill | fill | Line/area color |
border | border | New object structure: { color, width } |
markerSettings | markerSettings | Configuration object with visible, fill, size |
tooltipSettings | tooltipSettings | Requires service injection |
Data Binding Migration
EJ1:
// Direct array
dataSource: [10, 15, 12, 20]
// Object array with properties
dataSource: [
{ xVal: 'Jan', yVal: 100 },
{ xVal: 'Feb', yVal: 150 }
],
xName: 'xVal',
yName: 'yVal'EJ2:
// Same syntax, but with TypeScript typing
dataSource = [10, 15, 12, 20]
// Object array (TypeScript preferred)
dataSource = [
{ xVal: 'Jan', yVal: 100 },
{ xVal: 'Feb', yVal: 150 }
]
// In template:
xName="xVal"
yName="yVal"Marker Configuration Migration
EJ1 Marker Setup
$("#sparkline").ejSparkline({
markerSettings: {
visible: ['All'],
fill: 'red',
size: 5,
border: { color: 'blue' }
}
});EJ2 Marker Setup
@Component({
template: `<ejs-sparkline
[markerSettings]="markerConfig">
</ejs-sparkline>`
})
export class MarkerComponent {
markerConfig = {
visible: ['All'],
fill: 'red',
size: 5,
border: { color: 'blue' }
}
}Data Label Configuration Migration
EJ1 Data Labels
$("#sparkline").ejSparkline({
dataLabelSettings: {
visible: ['All'],
fill: 'white',
textStyle: {
color: 'black'
}
}
});EJ2 Data Labels
@Component({
template: `<ejs-sparkline
[dataLabelSettings]="labelConfig">
</ejs-sparkline>`
})
export class LabelComponent {
labelConfig = {
visible: ['All'],
fill: 'white',
textStyle: {
color: 'black'
}
}
}Tooltip Configuration Migration
EJ1 Tooltips
// EJ1: Tooltip via simple property
$("#sparkline").ejSparkline({
tooltip: {
visible: true,
template: 'Value: #point.y#'
}
});EJ2 Tooltips
// EJ2: Requires service injection + template syntax
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
template: `<ejs-sparkline
[tooltipSettings]="{
visible: true,
format: 'Value: ${y}'
}">
</ejs-sparkline>`
})
export class TooltipComponent { }Event Migration
EJ1 Events
// EJ1: jQuery event binding
$("#sparkline").ejSparkline({
pointRegionMouseEnter: function(args) {
console.log('Point entered:', args);
}
});EJ2 Events
// EJ2: Angular event binding
@Component({
template: `<ejs-sparkline
(pointRegionMouseEnter)="onPointEnter($event)">
</ejs-sparkline>`
})
export class EventComponent {
onPointEnter(args: any) {
console.log('Point entered:', args);
}
}Type System Migration
EJ1 Type Names
type: 'Line' // Line chart
type: 'Column' // Column chart
type: 'Area' // Area chart
type: 'Pie' // Pie chart
type: 'ColumnWinLoss' // Win-LossEJ2 Type Names
type="Line" // Line chart (same)
type="Column" // Column chart (same)
type="Area" // Area chart (same)
type="Pie" // Pie chart (same)
type="WinLoss" // Win-Loss (simplified)Complete Migration Example
EJ1 Implementation
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="ej.web.all.min.js"></script>
<link rel="stylesheet" href="ej.web.all.css" />
</head>
<body>
<div id="sparkline"></div>
<script>
var salesData = [
{ month: 'Jan', amount: 5000 },
{ month: 'Feb', amount: 7000 },
{ month: 'Mar', amount: 6500 }
];
$("#sparkline").ejSparkline({
dataSource: salesData,
type: 'Column',
xName: 'month',
yName: 'amount',
height: 100,
width: 250,
markerSettings: {
visible: ['High', 'Low'],
fill: 'red'
},
tooltip: {
visible: true
}
});
</script>
</body>
</html>EJ2 Implementation
import { SparklineModule, SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core'
@Component({
imports: [SparklineModule],
standalone: true,
providers: [SparklineTooltipService],
selector: 'app-root',
template: `<ejs-sparkline
[dataSource]="salesData"
type="Column"
xName="month"
yName="amount"
valueType='Category'
height="100px"
width="250px"
[markerSettings]="{
visible: ['High', 'Low'],
fill: 'red'
}"
[tooltipSettings]="tooltipSettings">
</ejs-sparkline>`
})
export class AppComponent {
salesData = [
{ month: 'Jan', amount: 5 },
{ month: 'Feb', amount: 7 },
{ month: 'Mar', amount: 6.5 }
]
tooltipSettings = {
visible: true,
format: '${month}: $${amount}k'
}
}Breaking Changes
Removed Features
The following EJ1 features are not available in EJ2:
| Feature | EJ1 | EJ2 | Workaround |
|---|---|---|---|
| URL-based data | ✓ | ✗ | Fetch data before binding |
| Print capability | ✓ | ✗ | Use browser print API |
| Export to image | ✓ | ✗ | Use dom-to-image library |
| Theme customizer | ✓ | ✗ | Use CSS custom properties |
Changed Default Values
| Property | EJ1 Default | EJ2 Default |
|---|---|---|
type | 'Column' | 'Line' |
height | 'auto' | '100px' |
fill | Varies | '#6200EE' |
Service Migration
EJ1 Services
// Services were implicit, no registration neededEJ2 Services
// Services must be explicitly injected
import { SparklineTooltipService } from '@syncfusion/ej2-angular-charts'
@Component({
providers: [SparklineTooltipService] // ← Required
})Testing and Validation
Test Checklist
After migrating, verify:
- [ ] Sparkline renders correctly
- [ ] Data displays accurately
- [ ] Markers appear in correct positions
- [ ] Data labels format correctly
- [ ] Tooltips show on hover
- [ ] Type changes work (Line, Column, Area, etc.)
- [ ] Colors apply correctly
- [ ] Responsive sizing works
- [ ] RTL support functions (if needed)
- [ ] Performance is acceptable with large datasets
Performance Comparison
EJ2 typically offers:
- 30-50% faster initial render
- 40% smaller bundle size (tree-shakeable)
- Better memory management with large datasets
- Improved event handling
Troubleshooting Migration Issues
Issue: Sparkline Not Rendering
Cause: Module not imported or service not provided.
Solution:
@Component({
imports: [SparklineModule], // ← Required
providers: [SparklineTooltipService] // ← If using tooltips
})Issue: Data Not Binding
Cause: Property names don't match data object.
Solution: Verify exact property names:
// ✓ Correct
xName="month" // Matches object property name
yName="amount"
// ✗ Wrong
xName="monthName" // Doesn't match
yName="value"Issue: Old jQuery Code Breaking
Cause: EJ2 doesn't support jQuery selectors.
Solution: Use Angular template binding instead:
// ✗ Old approach won't work
$("#sparkline").ejSparkline(...)
// ✓ New approach
@Component({
template: `<ejs-sparkline [dataSource]="data"></ejs-sparkline>`
})Resources
- Official Migration Guide: https://ej2.syncfusion.com/angular/documentation/sparkline/sparkline-types/
- API Reference: https://ej2.syncfusion.com/angular/documentation/api/sparkline/
- GitHub Examples: https://github.com/syncfusion/ej2-angular-samples
Getting Help
If you encounter migration issues:
1. Check the EJ2 API documentation 2. Review the feature comparison 3. Post on Syncfusion forums 4. Contact Syncfusion support
Sparkline Types
Table of Contents
- Overview
- Line Type
- When to Use Line Type
- Example: Stock Price Trend
- Customizing Line Appearance
- Column Type
- When to Use Column Type
- Example: Daily Website Visits
- Customizing Column Appearance
- Area Type
- When to Use Area Type
- Example: Monthly Revenue
- Pie Type
- When to Use Pie Type
- Example: Market Share Distribution
- Understanding Pie Sparkline Data
- Win-Loss Type
- When to Use Win-Loss Type
- Example: Test Results
- Simple Win-Loss with Primitives
- Type Comparison
- Selecting the Right Type
- Decision Guide
- Examples by Scenario
- Performance Considerations
Overview
The Sparkline component supports five visualization types, each optimized for different data patterns and use cases. The type is set using the type property.
Supported Types:
Line- Sequential trend visualization (default)Column- Discrete value comparisonArea- Filled area with trend emphasisPie- Proportional/compositional dataWinLoss- Binary outcomes (pass/fail, win/loss)
Line Type
Line sparklines display sequential data as a continuous line, ideal for showing trends over time.
When to Use Line Type
- Time series data - Stock prices, temperatures, sensor readings
- Trend analysis - Sales growth, website traffic, performance metrics
- Smooth progression - Data with continuous values
Example: Stock Price Trend
import { SparklineModule } from '@syncfusion/ej2-angular-charts'
import { Component } from '@angular/core';
@Component({
imports: [SparklineModule],
standalone: true,
selector: 'app-container',
template: `<ejs-sparkline
id='line-sparkline'
valueType='Category'
[dataSource]="stockPrices"
xName="day"
yName="price"
type="Line"
height="100px"
width="200px">
</ejs-sparkline>`
})
export class AppComponent {
stockPrices = [
{ day: 'Mon', price: 150 },
{ day: 'Tue', price: 152 },
{ day: 'Wed', price: 149 },
{ day: 'Thu', price: 155 },
{ day: 'Fri', price: 158 },
{ day: 'Sat', price: 156 },
{ day: 'Sun', price: 160 }
]
}Output: A line showing the price trend across the week.
Customizing Line Appearance
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Line"
[lineWidth]="2"
>
</ejs-sparkline>`
})
export class LineSparklineComponent {
data = [2, 6, 4, 8, 5, 1, 7]
}Key Properties:
lineWidth- Line thickness (default: 1)
Column Type
Column sparklines display data as vertical bars, effective for comparing discrete values or highlighting variations.
When to Use Column Type
- Value comparison - Sales by region, visits per day
- Discrete data - Different products, categories, locations
- Highlighting peaks and valleys - Easy to see spikes and dips
Example: Daily Website Visits
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
id='column-sparkline'
[dataSource]="dailyVisits"
xName="day"
yName="visits"
type="Column"
height="80px"
width="180px">
</ejs-sparkline>`
})
export class ColumnSparklineComponent {
dailyVisits = [
{ day: 1, visits: 120 },
{ day: 2, visits: 150 },
{ day: 3, visits: 110 },
{ day: 4, visits: 200 },
{ day: 5, visits: 180 },
{ day: 6, visits: 220 },
{ day: 7, visits: 200 }
]
}Output: Vertical bars showing visitor count each day.
Customizing Column Appearance
@Component({
template: `<ejs-sparkline
[dataSource]="data"
type="Column"
[fill]="'#4472C4'"
[rangeBandSettings]="{
start: 0,
end: 50,
color: '#F0F0F0'
}">
</ejs-sparkline>`
})
export class CustomColumnComponent {
data = [50, 120, 90, 130, 160, 140, 110]
}Area Type
Area sparklines combine a line with a filled area below, creating emphasis on trends while showing magnitude.
When to Use Area Type
- Revenue/profit trends - Shows total volume and direction
- Cumulative data - Network traffic, memory usage over time
- Magnitude emphasis - When magnitude matters as much as trend
Example: Monthly Revenue
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="monthlyRevenue"
xName="month"
yName="revenue"
valueType='Category'
type="Area"
height="100px"
width="250px"
[fill]="'rgba(68, 114, 196, 0.3)'">
</ejs-sparkline>`
})
export class AreaSparklineComponent {
monthlyRevenue = [
{ month: 'Jan', revenue: 5000 },
{ month: 'Feb', revenue: 7000 },
{ month: 'Mar', revenue: 6500 },
{ month: 'Apr', revenue: 8200 },
{ month: 'May', revenue: 9500 },
{ month: 'Jun', revenue: 8800 }
]
}Output: A filled area chart showing revenue growth.
Pie Type
Pie sparklines visualize proportional data, showing how parts relate to a whole.
When to Use Pie Type
- Market share - Product distribution, market segments
- Composition - Budget allocation, resource distribution
- Proportion visualization - Percentage breakdowns
Example: Market Share Distribution
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="marketShare"
xName="product"
yName="share"
type="Pie"
valueType='Category'
height="120px"
width="120px">
</ejs-sparkline>`
})
export class PieSparklineComponent {
marketShare = [
{ product: 'A', share: 30 },
{ product: 'B', share: 25 },
{ product: 'C', share: 20 },
{ product: 'D', share: 15 },
{ product: 'E', share: 10 }
]
}Output: A compact pie chart showing market distribution.
Understanding Pie Sparkline Data
For Pie sparklines, the yName values represent proportions. The values are automatically converted to percentages:
- If your data is [30, 25, 20, 15, 10], they sum to 100 and display as percentages directly
- If they don't sum to 100, they're normalized internally
Win-Loss Type
Win-Loss (or WinLoss) sparklines display binary outcomes as a series of positive and negative values, ideal for tracking success/failure patterns.
When to Use Win-Loss Type
- Success/failure tracking - Pass/fail tests, win/loss records
- Binary outcomes - Up/down stock movements, on/off states
- Pattern recognition - Quick visual identification of success streaks
Example: Test Results
@Component({
imports: [SparklineModule],
standalone: true,
template: `<ejs-sparkline
[dataSource]="testResults"
xName="test"
yName="result"
type="WinLoss"
height="80px"
width="200px">
</ejs-sparkline>`
})
export class WinLossSparklineComponent {
// Positive = Win (1), Negative = Loss (0 or -1)
testResults = [
{ test: 1, result: 1 },
{ test: 2, result: 1 },
{ test: 3, result: -1 },
{ test: 4, result: 1 },
{ test: 5, result: 1 },
{ test: 6, result: -1 },
{ test: 7, result: 1 }
]
}Output: Columns showing wins (positive) and losses (negative).
Simple Win-Loss with Primitives
// 1 = Win, -1 = Loss
dataSource = [1, 1, -1, 1, 1, -1, 1]
<ejs-sparkline
[dataSource]="dataSource"
type="WinLoss">
</ejs-sparkline>Type Comparison
| Type | Best For | Data Pattern | Visual |
|---|---|---|---|
| Line | Trends over time | Sequential, continuous | Continuous line |
| Column | Comparing values | Discrete categories | Vertical bars |
| Area | Magnitude + trend | Sequential, cumulative | Filled line area |
| Pie | Proportions | Parts of a whole | Colored pie slices |
| WinLoss | Binary outcomes | Pass/fail, win/loss | Positive/negative bars |
Selecting the Right Type
Decision Guide
Q1: Is your data continuous over time?
- Yes → Use
Line(smooth trend) orArea(emphasize magnitude) - No → Go to Q2
Q2: Is it about proportions or composition?
- Yes → Use
Pie - No → Go to Q3
Q3: Is your data binary (win/loss, pass/fail)?
- Yes → Use
WinLoss - No → Go to Q4
Q4: Are you comparing discrete values?
- Yes → Use
Column - Default → Use
Line
Examples by Scenario
| Scenario | Type | Reason |
|---|---|---|
| Stock price daily | Line | Continuous trend |
| Sales by region | Column | Discrete comparison |
| Network traffic | Area | Cumulative, volume matters |
| Budget breakdown | Pie | Proportional composition |
| Test pass/fail | WinLoss | Binary outcomes |
| Temperature daily | Line | Continuous trend |
| Product market share | Pie | Parts of whole |
| Success rate trend | Area | Trend + magnitude |
Performance Considerations
- Line - Fast rendering, large datasets (1000+ points)
- Column - Fast, 50-500 values
- Area - Fast, similar to Line
- Pie - Best with 3-10 slices
- WinLoss - Very fast, typically 5-50 points
For sparklines with 1000+ data points, prefer Column or Line types for better performance.