Ionic 2 — Generating new pages using the Ionic CLI

One common task when working on a Mobile application is to add new pages or views to your app. In Ionic Framework 1, this included adding an HTML template file, a JavaScript file for the Angular controller and some CSS or SASS code in either a new SASS file or in the apps CSS file.

In Ionic 2 the Ionic team has added a very nice new feature to the Ionic CLI. The ionic generate command. It lets you scaffold new files and directories in your app from the command line. So to add a new page, just run

$ ionic generate page MyNewPage

This little command will add the folling files to your project:

  • app\pages\my-new-page\my-new-page.html
  • app\pages\my-new-page\my-new-page.js
  • app\pages\my-new-page\my-new-page.scss

The scaffolded files have the following content:

my-new-page.html

<ion-navbar *navbar>
<ion-title>my-new-page</ion-title>
</ion-navbar>
<ion-content padding class=”my-new-page”>

</ion-content>

my-new-page.js

import {Page, NavController} from ‘ionic/ionic’;
@Page({
templateUrl: ‘build/pages/my-new-page/my-new-page.html’,
})
export class MyNewPage {
constructor(nav: NavController) {
this.nav = nav;
}
}

my-new-page.scss

.my-new-page {
}

So, from here you can go right ahead an use the new page in your app. For instance, you can start by navigating to it using the Ionic 2 router.

import {Page, NavController} from 'ionic/ionic';
import {MyNewPage} from '../my-new-page/my-new-page';
...
export class AnotherPage {
constructor(nav: NavController) {
this.nav = nav;
}
navigate() {
this.nav.push(MyNewPage);
}
}

Other very useful generators available are:

  • component
  • directive
  • pipe
  • provider
  • tabs

This little tool saves me lots of work and also helps keep the structure of the app in control.