How do you load a component in ionic 4 after the command ionic g component myComponent
? I want to add the custom component to my home page.
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 :-)
This is your selector in components>foot-card>foot-card.ts:
import { Component } from '@angular/core';
@Component({
selector: 'foot-card',
templateUrl: 'foot-card.html'
})
export class FootCardComponent {
text: string;
constructor() {
console.log('Hello FootCardComponent Component');
this.text = 'Hello World';
}
}
This is your components.module.ts:
import { NgModule } from '@angular/core';
import { FootCardComponent } from './foot-card/foot-card';
import { IonicModule } from 'ionic-angular';
@NgModule({
declarations: [FootCardComponent],
imports: [IonicModule],
exports: [FootCardComponent]
})
export class ComponentsModule {}
This is your app.module.ts:
import { FootCardComponent } from '../components/foot-card/foot-card';
import { ComponentsModule } from '../components/components.module'
@NgModule({
declarations: [
],
imports: [
ComponentsModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
FootCardComponent
],
providers: [
]
})
export class AppModule {}
You have to import component-module in import and declare component-name in entry components in add.module.ts.
In components.module.ts, You have to declare and export the component but don't forget to import IonicModule.
I was facing the same problem but no one told to import IonicModule In Components.module.ts and In app.module.ts, only add to entrycomponent and import componentmodule.
myComponent.html:
//Here your component HTML Code. For example:
<ion-list radio-group (ionSelect)="change($event, item.type);"
...
</ion-list>
components.module.ts:
import {myComponentComponent} from "./myComponent/myComponent";
@NGModule({
declatations: [myComponentComponent],
imports:[],
exports: [myComponentComponent]
})
export class ComponentsModule{}
app.module.ts:
import { MyComponentComponent } from "../components/myComponent/myComponent";
@NGModule({
declarations: [
yourPages....,
MyComponentComponent
]
)}
For example in HomePage.html:
<myComponent> </myComponent>