February 12, 2018
  • All
  • Desktop
  • Framework
  • Tutorials

Customizing Ionic Apps for Web & Mobile

Simon Grimm

This is a guest post from Simon Grimm, speaker and educator at Ionic Academy. Simon writes about Ionic frequently on his blog Devdactic.

With the development of Ionic apps comes the promise that your code will run on various platforms and screen sizes once it’s ready. While this can work and look fine on your targeted devices out of the box, it might not at first for everyone.

In this post, we’ll take a look at 4 areas to keep an eye on – especially if you plan to ship your Ionic app both as a website (or perhaps PWA?) and also as a native mobile app (perhaps even on phone and tablet devices).

Everything we need is already built into Ionic, but sometimes it’s easy to forget about all the awesomeness. So let’s get started with a tiny base for our examples!

App Starting Template Setup

For this article run the command below to start a new Ionic app with the side menu template:

ionic start devdacticResponsive sideMenu

It’s a super basic app with just 2 pages and a side menu (otherwise the name would be kinda bad) but we also need to make HTTP calls, therefore we use the new HttpClient which is available since Angular 5 and Ionic 3.9.0.

Simply change your app/app.module.ts to:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 declarations: [
   MyApp,
   HomePage,
   ListPage
 ],
 imports: [
   BrowserModule,
   IonicModule.forRoot(MyApp),
   HttpClientModule
 ],
 bootstrap: [IonicApp],
 entryComponents: [
   MyApp,
   HomePage,
   ListPage
 ],
 providers: [
   StatusBar,
   SplashScreen,
   {provide: ErrorHandler, useClass: IonicErrorHandler}
 ]
})
export class AppModule {}

That’s all we’ll need for our examples, so now let’s dive into our areas.

1. Responsive Grid Layout

Most Ionic components already adapt to screen changes and look good across various sizes. However, having something like a list item full size or an Ionic Card displayed full width on my large iMac screen kills my eyes. 😵

If you need your app to look good on a small device and in a desktop web browser, you’ll need to make it as responsive as possible. And what’s better then using the Ionic Grid layout system?

But first we need some data we can display inside a list, so let’s add a simple HTTP call to your pages/home/home.ts like this:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import "rxjs/add/operator/map";

@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
export class HomePage {

 users: Observable<any>;

 constructor(public navCtrl: NavController, private httpClient: HttpClient, private plt: Platform, private alertCtrl: AlertController) {
   this.users = this.httpClient.get('https://randomuser.me/api/?results=20')
   .map(res => res['results'])
 }
}

Now we have an array of users from the Randomuser API which we can display as cards. You could make this as simple iteration without any further testing, but if you’re serious about your design (which, of course you are!), you’ll want to make sure to test different sizes and breakpoints.

A breakpoint is a predefined value at which your design snaps from one category to the next. If your screen is smaller than 576px, you fall into the smallest category which is xs. However, at 577px your design will get the sm category applied, so you must prepare your design to also look good there, and at later breakpoints as well.

With Ionic, we can use the row and column system plus the breakpoints to build interfaces that look great across different platforms and adapt to display the best and most intuitive interface to the user.

Let’s take our example and add this code to our pages/home/home.html:

<ion-header>
 <ion-navbar>
   <button ion-button menuToggle>
     <ion-icon name="menu"></ion-icon>
   </button>
   <ion-title>Home</ion-title>
 </ion-navbar>
</ion-header>

<ion-content>
 <ion-grid>
   <ion-row>
     <ion-col *ngFor="let user of users | async" col-12 col-xl-2 col-lg-3 col-md-4>
       <ion-card>
         <ion-item>
           <ion-avatar item-start>
             <img [src]="user.picture.medium">
           </ion-avatar>
           <h2 text-capitalize>{{ user.name?.first }} {{ user.name?.last }}</h2>
         </ion-item>
         <ion-card-content>
           Bacon ipsum dolor amet salami prosciutto ham hock, strip steak buffalo ribeye pork chop. Beef ribs tenderloin tail shoulder.
           Spare ribs ham shoulder brisket rump hamburger. Pork belly kevin shoulder prosciutto ribeye pork chop chicken
           strip steak pig.
         </ion-card-content>
       </ion-card>
     </ion-col>
   </ion-row>
 </ion-grid>
</ion-content>

One Ionic row offers 12 units space for columns, so each column can take an amount of those 12. If your row takes 12 units, it means the row is already full and the next column will be displayed in the following row.

The syntax for the column isn’t immediately obvious, so let’s dive deeper into what it actually means:

  • col-12: If no other rules match, the column will take all 12 units (greedy column!)
  • col-md-4: At a minimum width of 768px, each column will only use 4 units. This means, a row can now handle 3 columns
  • col-lg-3: As the screen gets bigger than 992px, a column only needs 3 units which means the row how holds 4 columns
  • col-xl-2: On the largest screens (1200px+), a column only needs 2 units and a row will display 6 columns

In our example, a column always holds a card, so the design ranges from seeing only 1 card to 6 cards maximum (seen below).

Using a decent flexible layout is definitely mandatory if your app is going to run on multiple platforms and screen sizes. If you don’t invest time into doing this, your app might scare off potential users because it just looks odd.

There’s a lot more to the Grid like setting your own breakpoints, reordering columns, and more so go check it out!

2. CSS Media Queries

While we can’t really accredit this one directly to Ionic, we are still lucky that Ionic bets strongly on the Web and we can thus take advantage of languages like CSS, which most of us have all learned years ago.

Just like the grid layout, we can make use of breakpoints here as well by using @media and different sizes to change part of our UI.

In a recent app, we needed an ion-fabbutton at the top right corner on the web version as it was too hard to spot when it was at the far bottom right corner. However, on a mobile version of your app users are already familiar with having the button floating above lists at the bottom right.

This means the element needs exist in completely different places depending on screen size (and this is a simple element).

One way to achieve this is by having the element there twice, but only displaying it when the media query of your CSS matches. To do this, add the Fab button to your your pages/home/home.html after the list we already have:

<ion-fab right bottom class="web-fab">
 <button ion-fab icon-only color="primary" (click)="checkPlatform()">
   <ion-icon name="help"></ion-icon>
 </button>
</ion-fab>

<ion-fab right top edge class="mobile-fab">
 <button ion-fab icon-only color="primary" (click)="checkPlatform()">
   <ion-icon name="help"></ion-icon>
 </button>
</ion-fab>

If you want to make only one button visible, you could use the follow CSS inside your pages/home/home.scss:

page-home {
   @media (max-width: 576px) {
       ion-card-content {
           font-size: 2rem !important;
       }
   }

   @media (max-width: 820px) {
       .mobile-fab {
           display: none;
       }
   }

   @media (min-width: 820px) {
       .web-fab {
           display: none;
       }
   }
}

By using the media query you can of course do much more than hide and show elements by repositioning your elements. If you know where your elements should be exactly on the screen, you can also use just one element with the class.

For this example I wanted to use the Ionic values right bottom and top edge therefore I added the element twice instead of manually setting the position of the button.

With media queries you can customize the complete UI up to using a completely different UI for phone and tablet devices. It’s good to have this tool in your toolbox.

3. Checking Your Platform

Not only do we have to think about the UI of our app on different platforms, we should also understand on which platform(s) our app is running.

If your app runs inside a regular desktop browser you don’t need to call the Push notification setup, and you especially don’t want to make any calls to Cordova when running as a website!

To prevent this, simply inject the Platform whenever you need it and create checks to see on which platform you are running. As a test, open your pages/home/home.ts and change it to:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import "rxjs/add/operator/map";
import { Platform } from 'ionic-angular/platform/platform';
import { AlertController } from 'ionic-angular/components/alert/alert-controller';

@Component({
 selector: 'page-home',
 templateUrl: 'home.html'
})
export class HomePage {

 users: Observable<any>;

 constructor(public navCtrl: NavController, private httpClient: HttpClient, private plt: Platform, private alertCtrl: AlertController) {
   this.users = this.httpClient.get('https://randomuser.me/api/?results=20')
   .map(res => res['results'])
 }

 checkPlatform() {
   let alert = this.alertCtrl.create({
     title: 'Platform',
     message: 'You are running on: ' + this.plt.platforms(),
     buttons: ['OK']
   });
   alert.present();

   if (this.plt.is('cordova')) {
     // Do Cordova stuff
   } else {
     // Do stuff inside the regular browser
   }
 }
}

By checking this.plt.is('cordova') you can be sure that Cordova is available to your app, but you could also test for iOS / Android if you have specific code for those platforms.

One feature that’s especially different on a device and desktop browser is files. Inside your native app you will have a completely different file object (most of the time path to your app) then when you implement file upload for a browser.

If your app doesn’t need the feature on one or the other platform, no problem! But be aware that you have to keep an eye on testing your features on all targeted platforms to make sure everything’s working as planned.

4. Ionic Split Pane

One feature thing that makes desktop UI ready in seconds is the Ionic Split Pane.

We’ve already started an app with a side menu, so we only need to apply minimal changes to achieve a flexible dynamic UI that adapts to the screen size and automatically shows / hides our side menu.

Combine this approach with some CSS, and you get a (more or less) great looking web UI for your app. Don’t hate my color choices, this example is not about how I never became the designer I dreamed to be. 😂

So here’s what you need to change for your Split Pane inside the app/app.html:

<ion-split-pane when="sm">

 <ion-menu [content]="content">
   <ion-header>
     <ion-toolbar color="secondary">
       <ion-title>Menu</ion-title>
     </ion-toolbar>
   </ion-header>

   <ion-content class="menu-container">
     <ion-list no-lines>
       <button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)" class="transparent list-item">
         {{p.title}}
       </button>
     </ion-list>
   </ion-content>

 </ion-menu>

 <!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
 <ion-nav [root]="rootPage" #content main swipeBackEnabled="false"></ion-nav>
 </ion-split-pane>

With the side menu template, our menu is directly at the top of the app. Normally this would be perhaps in a later page (after a login) and therefore also the CSS would be in a different place.

For this example, we have to fit our additional CSS into the app/app.scss with some colors and changes to make the menu look more natural on the web:

<br />.split-pane-side {
   border-right: 0px !important;
}

.menu-container {
   background-color: color($colors, secondary);
}

.transparent {
   background: transparent;
}

.list-item {
   color: #ffffff;
   margin-bottom: 10px;
   font-size: 2rem;
}

:hover.list-item {
   background: #2e8015;
}

.scroll-content{
   overflow: hidden;
   margin-right: -17px;
   overflow-y: scroll;
}

The standard UI doesn’t look that good for a website, but of course with some CSS, colors, and hover effects (which you don’t really need for a mobile app) you can make the menu look like a standard menu you’re familiar with.

To further customise your Split Pane, you can override Ionic variables inside the theme/variables.scss so simply add this:

$split-pane-side-max-width: 12%;

Now your side menu won’t expand too far, and even look nice even on big screens!

Conclusion

It’s already epic to have one code base that can be built into a native mobile app and also be deployed to the web, but the flexibility of using some CSS and responsive items makes Ionic the perfect choice for both your next web application, PWA and mobile app!

To learn more about everything Ionic, check out the Ionic Academy, which offers a ton of courses on all related topics, projects to apply your knowledge in, and also a dedicated community with help for all your questions!

Good luck, and happy building!


Simon Grimm