Ionic 4 custom components

Yushin picture Yushin · Nov 7, 2018 · Viewed 26.9k times · Source

How do you load a component in ionic 4 after running the command ionic g component myComponent? I want to add a new generated custom component to my home page.

Answer

Steffen picture Steffen · Dec 9, 2018

Finally figured this out, here's a repro that works:

ionic start myProject blank --type=angular
ionic g module components
ionic g component components/myComponent --export

This adds both a declaration and export to the components module for "myComponent".

To use the component just add ComponentsModule to your imports in your page module, e.g.

@NgModule({
imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    ComponentsModule,
    RouterModule.forChild([
        {
            path: '',
            component: HomePage
        }
    ])
],
declarations: [HomePage]
})
export class HomePageModule { }

This way nothing is added to app.module.ts which is how it should be.

Also note if you want to use ANY components in your own custom components, you need to add IonicModule to the imports in components.module.ts

Hope this helps :-)