Skip to content

Instantly share code, notes, and snippets.

@gparlakov
Last active May 22, 2022 16:29
Show Gist options
  • Save gparlakov/3a0eec95fc991f760f0e033bb758716b to your computer and use it in GitHub Desktop.
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
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