0
votes

I am trying to apply gradient color for line chart in ng2-charts. But I am getting error

ERROR TypeError: Cannot read property 'nativeElement' of undefined

Code

<canvas #myCanvas [colors]="lineChartColors" ...
export class Demo {
  @ViewChild("myCanvas") canvas: ElementRef;
  lineChartColors;

// in ngOnInit
let gradient = this.canvas.nativeElement.getContext('2d').createLinearGradient(0, 0, 0, 200);
gradient.addColorStop(0, 'green');
gradient.addColorStop(1, 'white');
this.lineChartColors = [
  {
    backgroundColor: gradient
  }
];
1

1 Answers

0
votes

The HTML doesn't completely exist in the ngOnInit hook. you should do it inside ngAfterViewInit() function. The definition for this hook is

ngAfterViewInit() Respond after Angular initializes the component's views and child views / the view that a directive is in.

That means that the HTML is ready here, when you call it in in ngOnInit() you actually don't have this element on the page.

enter here for more info