DEV Community

Matthias Andrasch
Matthias Andrasch

Posted on • Updated on

Re-usable components in Ionic 6 Angular tabs-starter

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>
Enter fullscreen mode Exit fullscreen mode

Image description

<app-explore-container name="Tab 2 page"></app-explore-container>
Enter fullscreen mode Exit fullscreen mode

Image description

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. 🤦

Forehead Slap Slapping Forehead GIF

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 {}
Enter fullscreen mode Exit fullscreen mode

Source code

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 {}
Enter fullscreen mode Exit fullscreen mode

Source code

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)