Search code examples
angularionic-frameworkchartscomponents

Cannot render custom component in Ionic Angular app- import issue


I have a custom component to render a bar chart. The selector is:

@Component({
  selector: 'app-bar-chart-component',
  templateUrl: './bar-chart-component.component.html',
  styleUrls: ['./bar-chart-component.component.scss'],
})

When I try to render the component in a separate page (tab2page.html) I get error:

 <app-bar-chart-component></app-bar-chart-component>

Error: src/app/tab2/tab2.page.html:22:3 - error NG8001: 'app-bar-chart-component' is not a known element:

  1. If 'app-bar-chart-component' is an Angular component, then verify that it is part of this module.
  2. If 'app-bar-chart-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.

I have import the component in tab2.module.ts so not sure where its missing:

import { BarChartComponentComponent } from '../components/bar-chart-component/bar-chart-component.component';

Have also imported and declared in app.module.ts :

@NgModule({
  declarations: [AppComponent, BarChartComponentComponent, LineChartComponentComponent, PieChartComponentComponent],
  //declarations: [AppComponent],
  imports: [ NgChartsModule, BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})

Question is where do I need to import the component to render to in tab2 page?


Solution

  • If you want to re-use your custom component in multiple other components, you will have to create a module that exports your component.

    Let's call it ChartModule.

    @NgModule({
      declarations: [BarChartComponentComponent],
      exports: [BarChartComponentComponent]
    });
    export class ChartModule {}
    

    You need to add your component that you want to use in declarations and you need to add it to exports, otherwise it will not be available when another modules imports this module.

    Now you can import this module in any other module and your component will be available.

    Let's say that you want to add it to your tab2.module. In that module you then import your ChartModule and that will then make your BarChartComponentComponent to use in any component that is declared in that module.

    No you can add any of your other chart components in the ChartModule and they will then also be available in any module that imports the ChartModule