Implement Dynamic Theming with ThemeService
masterThe ThemeService allows you to apply color overrides to charts when a theme changes. You can pass a ChartOptions object to setColorschemesOptions().
Override Behavior:
- Simple fields: Replaces the matching field in the chart's
optionsobject. - Arrays: If an array is encountered (e.g.,
xAxesoryAxes), the single object provided in the override acts as a template to update all elements within that array.
type Theme = 'light-theme' | 'dark-theme';
private _selectedTheme: Theme = 'light-theme';
public get selectedTheme() {
return this._selectedTheme;
}
public set selectedTheme(value: Theme) {
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
overrides = {
legend: {
labels: { fontColor: 'white' }
},
scales: {
xAxes: [{
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
}],
yAxes: [{
ticks: { fontColor: 'white' },
gridLines: { color: 'rgba(255,255,255,0.1)' }
}]
}
};
} else {
overrides = {};
}
this.themeService.setColorschemesOptions(overrides);
}
constructor(private themeService: ThemeService<AppChartMetaConfig)) {}
setCurrentTheme(theme: Theme) {
this.selectedTheme = theme;
}