chart-color.service.ts
import { Injectable } from '@angular/core';
import { ChartOptions } from 'chart.js';
import { ThemeService } from 'ng2-charts';
// 搬到外面,在 class 內會一直錯誤
type Theme = 'light-theme' | 'dark-theme';
@Injectable({
providedIn: 'root'
})
export class ChartColorService {
onstructor(private themeService: ThemeService) { }
private _selectedTheme: Theme = 'light-theme';
setCurrentTheme(theme: Theme): void {
this.selectedTheme = theme;
}
public get selectedTheme() {
return this._selectedTheme;
}
public set selectedTheme(value) {
this._selectedTheme = value;
let overrides: ChartOptions;
if (this.selectedTheme === 'dark-theme') {
// 黑暗版本
overrides = {
title: {
fontColor: 'yellow'
},
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 = {
title: {
fontColor: 'blue'
},
legend: {
labels: { fontColor: 'red' }
},
scales: {
xAxes: [{
ticks: { fontColor: 'black' }, // 標示數值的顏色
gridLines: { color: 'rgba(255,255,255,0.1)' }, // 底線 和 | 線的顏色
scaleLabel: { fontColor: 'green' } // 標示文字顏色
}],
yAxes: [{
ticks: { fontColor: 'red' },
gridLines: { color: 'rgba(255,255,255,0.1)' } // 左側線 和 --- 線的顏色
}]
}
};
}
this.themeService.setColorschemesOptions(overrides);
}
}
app.component.ts
constructor(
private chartColorService: ChartColorService) {
}
// ngOnInit 設定要把個版本,就會把設定覆蓋寫進 顏色模板了
this.chartColorService.selectedTheme = 'light-theme';