Search code examples
angularchart.jspie-chartng2-chartsangular18

Upgrading to latest angular 18 with ng2-charts errors on nsg-serve


Upgrading angular 18 with ng2-charts 6.0.1 on running n-serve throws error as below imports ng2-charts, chart.js,chartjs-plugin-annotation. nothig helps and throws error.

I am trying to use in npn -standard component which is child component for other modules.

    X [ERROR] NG8002: Can't bind to 'type' since it isn't a known property of 'canvas'. [plugin angular-compiler]

    src/app/shared/tt-chart/tt-chart.component.html:64:32:
      64 │ ...   <canvas baseChart [type]="pieChartType" class="chart" [datas...
         ╵                         ~~~~~~~~~~~~~~~~~~~~~

  Error occurs in the template of component TTChartComponent.

    src/app/shared/tt-chart/tt-chart.component.ts:11:15:
      11 │   templateUrl: './tt-chart.component.html',
         ╵                ~~~~~~~~~~~~~~~~~~~~~~~~~~~


X [ERROR] NG8002: Can't bind to 'datasets' since it isn't a known property of 'canvas'. [plugin angular-compiler]

    src/app/shared/tt-chart/tt-chart.component.html:64:68:
      64 │ ...pe" class="chart" [datasets]="pieChartData[i]" [labels]="chartL...
         ╵                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  Error occurs in the template of component EfChartComponent.

    src/app/shared/tt-chart/tt-chart.component.ts:11:15:
      11 │   templateUrl: './tt-chart.component.html',
         ╵                ~~~~~~~~~~~~~~~~~~~~~~~~~~~

Solution

  • Go through each of the error component and apply the below approach ( This errors happens when the BaseChartDirective is not imported ).

    If task component is standalone, add BaseChartDirective to the imports array.

    import { BaseChartDirective } from 'ng2-charts';
    ...
    
    ...
    @Component({
        standalone: true,
        imports: [
          ...
          BaseChartDirective,
          ...
        ],
        ...
    })
    export class TaskComponent {
        ...
    

    If the task is not standalone, go to the place where you delared the component declarations array. Then import FormModule.

    import { BaseChartDirective } from 'ng2-charts';
    ...
    
    ...
    @NgModule({
        ...
        imports: [
          ...
          BaseChartDirective,
          ...
        ]
        ...
    })
    export class SomeModule {}
    

    Also ensure you main.ts has the below code.

    import { provideCharts, withDefaultRegisterables } from 'ng2-charts';
    
    bootstrapApplication(AppComponent, {
      providers: [provideCharts(withDefaultRegisterables())],
    }).catch((err) => console.error(err));
    

    The official npm docs provides you step by step on how to configure.