There are some good tutorials for creating re-usable components in Ionic 6, e.g. Create Reusable Progress Bar Component. While those tutorials seem to work in some of the provided starter options of Ionic (blank, sidemenu, etc.), they fail in the tabs-starter.
While I was setting up a fresh demo repository to share my error message with my fellow developers, I noticed something strange:
There was already a component which was re-used on multiple tabs:
<app-explore-container name="Tab 1 page"></app-explore-container>
<app-explore-container name="Tab 2 page"></app-explore-container>
And - the strangest thing was - it just worked on all tab pages!
Turns out ... I deleted this example component early on in my Ionic app and totally forgot about it. 🤦
After investigating the source code of the tabs-starter, I learned the following:
You need to define a module for your component first!
/* explore-container.module.ts */
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { ExploreContainerComponent } from './explore-container.component';
@NgModule({
imports: [ CommonModule, FormsModule, IonicModule],
declarations: [ExploreContainerComponent],
exports: [ExploreContainerComponent]
})
export class ExploreContainerComponentModule {}
And finally the module (instead of the component) must be imported into every tab module where we want to use it:
/* tab1.module.ts */
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 { ExploreContainerComponentModule } from '../explore-container/explore-container.module';
import { Tab1PageRoutingModule } from './tab1-routing.module';
@NgModule({
imports: [
IonicModule,
CommonModule,
FormsModule,
ExploreContainerComponentModule,
Tab1PageRoutingModule
],
declarations: [Tab1Page]
})
export class Tab1PageModule {}
I'm not quite sure yet how the module creation is done correctly via ionic-cli, it should be something like that with ionic generate:
ionic generate module explore-container/explore-container
See e.g. "Create component & add it to a specific module with Angular-CLI" discussion on stackoverflow for more information.
Happy to hear your solutions in the comments!
Top comments (0)