Add custom component – Ionic 5
Hi, Buddy, Today we are going to learn how to add custom component in the ionic 5 app. Sometimes we want to use some UI snippets over multiple pages. So, custom components are the best way to do so.
Generate Custom Component
To generate the component by ionic CLI, run the following command.
ionic generate component components/my-component
It will generate MyComponent files in the app/components directory. Normally it adds the components files in the app directory but we want to keep all components in a separate directory that’s why I used the components directory while generating the new component.
Add a file called share-component-module.ts in the components directory. Now the directory structure will look like below in the screenshot.
Edit component module file
Now open the share-component.module.ts file and add the my-component to it. We need to add it to the declaration array and exports array. You can copy paste below code to this file.
import { CommonModule } from '@angular/common'; import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { IonicModule } from '@ionic/angular'; import { MyComponentComponent } from './my-component/my-component.component'; @NgModule({ declarations: [MyComponentComponent], schemas: [ CUSTOM_ELEMENTS_SCHEMA ], imports: [ CommonModule, IonicModule ], exports: [MyComponentComponent] }) export class ShareComponentModule {}
Now, we are ready to go. We can use our component anywhere in the app. Like if we have a tab based app and want to add our component in the tab1 page. Then we need to include our share-component-module to the module file of the tab1 page. Like below.
import { IonicModule } from '@ionic/angular'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { Tab1Page } from './tab1.page'; import { Tab1PageRoutingModule } from './tab1-routing.module'; import { ShareComponentModule } from 'src/app/components/share-component.module'; @NgModule({ imports: [ IonicModule, CommonModule, FormsModule, Tab1PageRoutingModule, ShareComponentModule ], declarations: [Tab1Page] }) export class Tab1PageModule {}
Now, we can use my-component on the tab1 page. If we are not using lazy loading then we can include our share-component-module to app-module file directly. Here is how we can use the component on this page.
<my-component></my-component>
It will not only load the my component html snippet here but also load the my-component ts file working if something is there. Like if we are fetching some data through the api to my-component ts file and then view it to our html page. Everything will work in the same way on another page also where this component will be included.
Hope you find this article useful. If you have any query or suggestion plz comment below.