Last active
May 22, 2022 16:29
-
-
Save gparlakov/3a0eec95fc991f760f0e033bb758716b to your computer and use it in GitHub Desktop.
Wrap chart js constructor in a function and provide it with an InjectionToken
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function chartBuilder(item: ChartItem, options: ChartConfiguration) { | |
return new Chart(item, options); | |
} | |
// The 👆 function and the Token 👇 | |
const ChartBuilderToken = new InjectionToken<typeof chartBuilder>( | |
'The Chart.js instance builder' | |
); | |
@Component({ | |
..., | |
// provide it 👇 | |
providers: [{ provide: ChartBuilderToken, useValue: chartBuilder }], | |
}) | |
export class ChartComponent { | |
@ViewChild('canvas') | |
canvas: ElementRef | undefined; | |
chart: Chart | undefined; | |
constructor( | |
// 👇 use the special Inject syntax to tell Angular what you want | |
@Inject(ChartBuilderToken) private buildChart: typeof chartBuilder | |
) {} | |
ngAfterViewInit() { | |
this.chart = this.buildChart(this.canvas?.nativeElement, { /*...*/ }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment