Ionic Tutorials: Sorting modules in ionic 4

in #utopian-io5 years ago

ionic.jpg
image source

Repository: Ionic Github Repository

Software Requirements:
Visual Studio Code(Or any preferred code editor),
npm, ionic.

What you will learn:
In this tutorial you would learn about how to manage your ionic/Electron app on whatever platform you choose to target covering these major concepts

  • How to use a component within a normal page
  • How to use a component within a modal
  • How managing modules affects performance with lazy loading

Tutorial

I recently fully migrated to ionic 4 and am almost fully done with a project. If you're new to 4 and have been following my tutorials or are familiar with ionic but not four. Then this tutorial would go a long way in helping you get familiarized with ionic 4.
Today I would be covering how you should sort modules which in the ionic 4 documentation is really poor. I guess they want you to figure it out yourself. Ionic 4 uses angular routing so the mechanism is quite different and every single page is lazy loaded to increase performance. For this reason using popovers within modals can pose problematic and understanding what modules to load on startup.

Let get started with Popovers

Popovers

To use popovers, you have to use a custom component and load it within your other page,
When being loaded on a normal navigated page.
Start up a new project with the command

ionic start newProject blank

And when the whole folder is downloaded and fully installed you can create a new page called the tutorial page with

ionic g page tutorial

Note: If you're a web developer you could also use angular commands within your ionic project to make things more convenient as the newest ionic is built more closely with angular. So an alternative command may be

ng generate page tutorial

Angular uses routing so navigating to this page would be easy using a simple router link

[routerLink]='tutorial'.

This would navigate to your tutorial page from your home page by looking for 'tutorial' within your app.routing.module and sending you to the module that matches this. Your app.routing.module should look like this

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: '', loadChildren: './menu/menu.module#MenuPageModule' },
  { path: 'tutorial', loadChildren: './tutorial/tutorial.module#TutorialPageModule' },//This is where our router looks to redirect our page
{ path: 'home',loadChildren: './home/home.module#HomePageModule'}
];
@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {}

So bind that routerLink to a button as shown earlier and navigate to the new tutorial page and then we can add a simple button in the header to create our pop up
The template code should look like this

<ion-header>
   <ion-toolbar>
      <ion-buttons slot='start'>
      <ion-button (click)="showPopover($event)"><ion-icon></ion-icon><ion-button>
</ion-buttons>
      <ion-title>Tutorial Page</ion-title>
</ion-toolbar>
</ion-header>

And the code to show the popover should be

async showPopover(event) {
    let popover = await this.popoverCtrl.create({
      component: Popover1Component,
      backdropDismiss: false,
      translucent: true,
      id: '1',
      event: event
    })
      })
    return await popover.present();

  }

You then use

ionic g component popover1

To create the template we would use within our popover and which would be bound to this page.
You could use anything within your template as this is a tutorial but ill be using an example for a template that shows some priorities for you to choose from

<ion-list>
  <ion-radio-group [(ngModel)]="priority">
      <ion-list-header>
          Set Priority
        </ion-list-header>
        <ion-item>
            <ion-label>
              Due Date
            </ion-label>
            <ion-radio slot="start" value='dueDate' checked></ion-radio>
          </ion-item>
          <ion-item>
            <ion-label>
              Higher Amounts First
            </ion-label>
            <ion-radio slot="start" value='hAmount'></ion-radio>
          </ion-item>
          <ion-item>
            <ion-label>
              Lesser Amounts First
            </ion-label>
            <ion-radio slot="start" value='lAmount'></ion-radio>
          </ion-item>
  </ion-radio-group>
  <ion-button (click)="close()" expand="full">Close</ion-button>
</ion-list>

Screenshot (5).png

So now that we have everything in place we can then proceed to the main purpose of this tutorial which would be to explain the modules. Since this is a normal page we can load our popover easily but we would need to add it to the module of the page which is presenting it.
Head to tutorial.module.ts
And look at the code below at entryComponents and declarations where i declared the component.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { TutorialPage } from './tutorial.page';
import { Popover1Component } from '../popover1/popover1.component';

const routes: Routes = [
  {
    path: '',
    component: TutorialPage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  entryComponents: [Popover1Component],//Entry component here
  declarations: [TutorialPage,Popover1Component]//Declarations here
})
export class TutorialPageModule {}

This is the normal recommended way to use a popover within another
But what if the tutorial page was a modal, what then

Modals

A modal is a component and is loaded from the main module of the app, the problem with using components within modals is that the component cannot be declared within a module that exists in another module. They have to be managed to exist at the same level and you would get an error telling you to send your module for the component to a higher page. To undertand this, lets present this page as a modal instead.

async openTutorialPageAsModal(){
    const tutorialPage = await this.modalCtrl.create({
        component: 'TutorialPage',
       })
  return await tutorialPage.present()
}

And because the whole of ionic 4 uses lazy loading, we would have to add this page to the module which is within our home page. Head to home.module.ts and add 'tutorialPage` to your declarations and entryComponents as we saw earlier

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { IonicModule } from '@ionic/angular';

import { TutorialPage } from './tutorial.page';
import { Popover1Component } from '../popover1/popover1.component';

const routes: Routes = [
  {
    path: '',
    component: HomePage
  }
];

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    RouterModule.forChild(routes)
  ],
  entryComponents: [TutorialPage],
  declarations: [TutorialPage,Home Page]
})
export class HomePageModule {}

Dont Panic: This should give us an error
Angular routing manages modules and makes use modules as optimized as possible which means that it should not be declared on a page where it would not be used. But because of this effect, the popover component cannot load within a page that already exist under another module. This means that the solution would be to move the tutorial page to a point where it directly part of the apps module and so head to your app.module.ts and add the page that it is being loaded in in this module.
It should look like this

import { TutorialPage } from './tutorial/tutorialpage.ts'
import { TutorialPageModule } from './tutorial/tutorialpage.module.ts'
@NgModule({
  declarations: [AppComponent],
  entryComponents: [TutorialPage],//And here
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,ClearDebtPageModule,TutorialPageModule,//It should be added here
    IonicStorageModule.forRoot(),
  ],
  providers: [
    StatusBar,
    TabsService,
    SplashScreen,
    LocalNotifications,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Look within the code for comments to see where it was added.
Now our popover should work

Managing modules and performance

Ionic has never been the master of performance when compared to react and other native based frameworks but angular has made it as optimized as possible by using lazy loading and only creating pages when they are needed so as not to clog the performance space given to the web view of our app. You learning to manage your modules helps to improve performance because the less modules loaded at startup increases things like boottime and in app performance. With the knowledge of this try as much as possible to load as little as you can while running your app so that it would run seamlessly on highgrade and lower grade devices alike.

See you in the next
You can find on Github

Sort:  

Thank you for your contribution @yalzeee.
We've been reviewing your contribution and suggested the following points for your next tutorial:

  • Use shorter paragraphs and give breaks between them. It will make it easier to read your tutorial.

  • Put more screenshots of the results you are having during your tutorial.

  • We suggest you put comments in your code sections. We have already suggest in your previous tutorials that it is important to have comments in the code because it helps less experienced readers better understand what you are developing.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @yalzeee!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Hey, @yalzeee!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.28
TRX 0.13
JST 0.032
BTC 60793.50
ETH 2910.51
USDT 1.00
SBD 3.59