Search Lessons, Code Snippets, and Videos
search by algolia
X
#native_cta# #native_desc# Sponsored by #native_company#

Organize Shared Components in an Ionic 4 App

written by Jeff Delaney
full courses and content on fireship.io

Keeping your Ionic app organized is critical not just for performance, but also for developer happiness. The following snippet will show you how to (1) create a shared component module for your app and (2) create a lazy loaded feature module with zero configuration.

Shared Ionic Component Module

A shared component module is useful for elements that you expect to use in multiple features - things like loading spinners, login buttons, brand UI elements, advertisements, etc.

One of the first actions I take in a new app is to generate a shared module.

ionic g module shared

This creates a new folder to fill with components, but make sure they are exported.

ionic g component shared/profile --export
ionic g component shared/login --export
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';

import { LoginComponent } from '../shared/login/login.component';
import { ProfileComponent } from './profile/profile.component';

@NgModule({
imports: [
CommonModule,
IonicModule
],
declarations: [
LoginComponent,
ProfileComponent
],
exports: [
LoginComponent,
ProfileComponent
]
})
export class SharedModule {}

Now you can import these components into other modules and consume them:

@NgModule({
imports: [
CommonModule,
SharedModule
]
})
export class SomeOtherModule {}

Lazy Loaded Feature Module

I love lazy loading in Ionic 4 so much that I tweeted about it.

It’s really easy to build high-performance features in Ionic because there is zero configuration required for lazy loading (or Webpack code splitting to be precise). When you run the ionic g page command it automatically adds the lazy loading boilerplate in Angular, which is a pain to deal with manually.

ionic g page user-profile

ionic g component user-profile/avatar
ionic g component user-profile/bio
ionic g component user-profile/settings

These components are not needed outside of the UserProfilePage, so it is best to keep them nested inside the parent page where they will be lazy loaded and easier to manage in isolation.