Project Structure
Let’s walk through the anatomy of an Ionic 2 app. Inside of the folder that was created, we have a typical Cordova project structure where we can install native plugins, and create platform-specific project files. The bulk of our application lives inside the app
folder, and so we are going to spend most of our time there.
./www/index.html
www/index.html
is the main entry point for the app, though its purpose is to set up script and CSS includes and bootstrap, or start running, our app. We won’t spend much of our time in this file.
For your app to function, Ionic looks for the <ion-app>
tag in your HTML. In this example we have:
<ion-app></ion-app>
And the following scripts near the bottom:
<script src="cordova.js"></script>
<script src="build/js/app.bundle.js"></script>
-
build/js/app.bundle.js
is a concatenated file containing Ionic, Angular and your app’s JavaScript. -
cordova.js
will 404 during local development, as it gets injected into your project during Cordova’s build process.
./app/app.js
Inside of the app
directory we find our pre-compiled code. This is where most of the work for an Ionic 2 app will take place. When we run ionic serve
, our code inside of app/
is transpiled into the correct Javascript version that the browser understands (currently, ES5). That means we can work at a higher level using TypeScript and ES6+, but compile down to the older form of Javascript the browser needs.
app/app.js
is the entry point for our app.
Near the top of the file, we should see this:
@App({
templateUrl: 'build/app.html'
})
class MyApp {
constructor() {
}
}
Every app has a root component that essentially controls the rest of the application. This is very similar to ng-app
from Ionic and Angular 1. To specify a root component with Ionic, we use the @App
decorator.
In this component, we set the template to be the file at build/app.html
, which is a compiled version of app/app.html
, let’s take a look!
./app/app.html
Here’s the main template for the app in app/app.html
:
<ion-menu [content]="content">
<ion-toolbar>
<ion-title>Pages</ion-title>
</ion-toolbar>
<ion-content>
<ion-list>
<button ion-item *ngFor="#p of pages" (click)="openPage(p)">
{{p.title}}
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav id="nav" [root]="rootPage" #content swipe-back-enabled="false"></ion-nav>
In this template, we set up an ion-menu
to function as a side menu, and then an ion-nav
component to act as the main content area. The ion-menu
’s [content]
property is bound to the local variable content
from our ion-nav
, so it knows where it should animate around.
Next let’s see how to create more pages and perform basic navigation.