34,79 €
Ionic is the preferred choice for JavaScript developers to develop real-time hybrid applications. This book will get you started with Ionic 3.9 and help you create Angular 5 components that interact with templates.
You will work with Ionic components and find out how to share data efficiently between them. You'll discover how to make the best use of the REST API to handle back-end services and then move on to animating your application to make it look pretty. You then learn to add in a local push notification in order to test the app. Then you'll work with Cordova to support native functionalities on both iOS and Android. From there, you'll get to grips with using the default themes for each platform and customizing your own. We then take you through the advanced Ionic features like lazy loading, deep linking, localizing ionic apps etc. Finally, you'll see how best to deploy your app to different platforms.
This book will solve all your Ionic-related issues through dedicated recipes that will help you get the best out of Ionic.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing or its dealers and distributors will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Amarabha BanerjeeAcquisition Editor: Isha RavalContent Development Editor: Mohammed Yusuf ImaratwaleTechnical Editor: Diksha WakodeCopy Editor: Safis EditingProject Coordinator: Hardik BhindeProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Jason MonteiroProduction Coordinator: Nilesh Mohite
First published: November 2016 Second edition: October 2015 Third edition: April 2018
Production reference: 1260418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-323-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Indermohan Singhis a Mobile App Developer working in Vienna, Austria, originally from Ludhiana, Punjab. For the past 3 years, he has worked on Angular, Ionic, and TypeScript most of the time. He authored Ionic 2 Blueprint for Packt Publishing, and this is his second book on the subject. Before starting the full-time job, he was freelancer with many startups. During his time as a freelancer, he also mentored learners at codementor.io, where he was mostly teaching JavaScript. He is also hobbyist musician and loves to create Indian Compositions and play them on harmonium.
Hoc Phan is a technologist with experience in frontend development, cloud computing, and big data. He started programming at the age of 12. Hoc has worked on many JavaScript projects by learning from various online sources and was one of the first few developers who tested Ionic for its feasibility as a JavaScript replacement of the native language of a device. He authored the Ionic Cookbook. He frequently speaks at local meetups and cloud computing/big data industry events and conferences. He holds an MBA degree from the University of Washington's Michael G. Foster School of Business.
Nitish Sinha, a techie from Jharkhand, is a hardcore believer of Steve Jobs’s words, "The only way to do great work is to love what you do.". Working as a software developer in a reputed firm, he is quite passionate about learning and unlearning things. He has a vast amount of experience in technologies like Angular.js, Node.js, Ionic Framework, and such.
He strongly believes in adapting oneself to an ever-evolving IT sphere, and learning upcoming technologies is his core strength. Not only that, he believes in sharing the learned wisdom with others.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Ionic Cookbook Third Edition
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the authors
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Sections
Getting ready
How to do it...
How it works...
There's more...
See also
Get in touch
Reviews
Creating Our First App with Ionic
Introduction
Setting up a development environment
Getting ready
How to do it...
There's more...
Creating a HelloWorld app via the CLI
How to do it...
How it works...
Creating a HelloWorld app via Ionic Creator
Getting ready
How to do it...
There's more...
Viewing the app using your web browser
Getting ready
How to do it...
How it works...
Viewing the app using the Ionic CLI
Getting Ready
How to do it...
Viewing the app using Xcode for iOS
How to do it...
There's more...
Viewing the app using Genymotion for Android
How to do it...
Viewing the app using Ionic View
How to do it...
There's more...
Adding Ionic Components
Introduction
Adding multiple pages using tabs
Getting ready
How to do it...
How it works...
See also
Adding left and right menu navigation
Getting ready
How to do it...
How it works...
See also
Navigating multiple pages with state parameters
Getting ready
How to do it...
How it works...
See also
Using menu, tabs, and segment together in an app
Getting ready
How to do it...
How it works...
See also
Using the Ionic grid to create a complex UI
Getting ready
How to do it...
How it works...
See also
Extending Ionic with Angular Building Blocks
Introduction
Creating a custom pizza ordering component
Getting ready
How to do it...
How it works...
See also
Creating a custom username input directive
Getting ready
How to do it...
How it works...
See also
Creating a custom pipe
Getting ready
How to do it...
How it works...
See also
Creating a shared service to provide data to multiple pages
Getting ready
How to do it...
How it works...
See also
Reusing an existing page as an HTML element
Getting ready
How to do it...
How it works...
See also
Validating Forms and Making HTTP Requests
Introduction
Creating a complex form with input validation
Getting ready
How to do it...
How it works...
See also
Creating reactive forms in Ionic
Getting ready
How to do it...
How it works...
See also
Retrieving data via a mocked API using a static JSON file
Getting ready
How to do it...
How it works...
See also
Integrating with Stripe for online payment
Getting ready
How to do it...
How it works...
See also
Adding Animation
Introduction
Embedding full screen inline video as background
Getting ready
How to do it...
How it works...
Creating physics-based animation using Dynamics.js
Getting ready
How to do it...
How it works...
See also
Animating the slide component by binding a gesture to the animation state
Getting ready
How to do it...
How it works...
See also
Adding a background CSS animation to the login page
Getting ready
How to do it...
How it works...
See also
User Authentication and Push Notifications
Introduction
Registering and authenticating users using Auth0
Getting ready
How to do it...
Creating our app in the Auth0 dashboard
Let's code
How it works
There's more...
Building an iOS app to receive push notifications
Getting ready
How to do it
Let's create an Apple signing certificate
Adding a device and creating the provisioning profile
Creating a push certificate
Now let's configure OneSignal
Let's code
How it works
There's more...
Building an Android app to receive push notifications
Getting ready
How to do it
Configuring Firebase for push notifications
Configuring OneSignal
Let's code now
How it works
There's more...
Supporting Device Functionalities Using Ionic Native
Introduction
Taking a photo using the camera plugin
Getting ready
How to do it...
How it works...
There's more...
Sharing content using the social sharing plugin
Getting ready
How to do it...
How it works...
There's more...
Displaying a local notification using the local notification plugin
Getting ready
How to do it...
How it works...
There's more...
Fingerprint authentication using the fingerprint AIO plugin
Getting ready
How to do it...
How it works...
There's more...
Creating a media player with the Media Player notification control
Getting ready
How to do it...
How it works...
There's more...
Creating a taxi app using the Google Maps plugin and geocode support
Getting ready
How to do it...
How it works...
There's more...
Theming the App
Introduction
Viewing and debugging themes for a specific platform
Getting ready
How to do it...
How it works...
There's more...
Customizing themes based on the platform
Getting ready
How to do it...
How it works...
There's more...
Advanced Topics
Introduction
Lazy loading in Ionic
Getting ready
How to do it...
How it works...
There's more...
See also
Internationalization (i18n) using ngx-translate
Getting ready
How to do it...
How it works...
See also
Creating documentation for Ionic app
Getting ready
How to do it...
How it works...
See also
Publishing the App for Different Platforms
Introduction
Adding versioning to future-proof the app
Getting ready
How to do it...
How it works...
Building and publishing an app for iOS
Getting ready
How to do it...
How it works...
There's more...
Building and publishing an app for Android
Getting ready
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
Mobile application development has been a hot topic for quite a while now. There are multiple platforms and devices with different screen sizes and form factors out there to accommodate. It makes mobile app development very difficult. Luckily, Ionic is one such tool that helps us mitigate this very problem by allowing us to write code once for all platforms and devices.
In this book, readers will learn how to create mobile applications using Ionic. We will start with very basic things, such as setting up the development environment, using Navigation in apps, working with backend via REST API, Animations, Authenticating Users, Receiving push notifications, localizing an app, generating documentation, and publishing the app, to name a few. Readers will also learn things about Angular and Ionic CLI. I hope that this book will help novice developers as well as advanced developers, because the content is a mixture of easy and advance ionic stuff.
Ionic Cookbook is for front-end developers who want to create cross-platform mobile apps. This book will help you become a Mobile App developer who is comfortable enough to take on difficult apps by teaching readers about Angular, Cordova, and Sass in depth. The intention of this book is to teach Ionic by solving real-world problems like authentication, push notifications, using the camera to name a few. Nevertheless, if you are new to front-end development, you will still be able to follow the book.
Chapter 1, Creating Our First App with Ionic, introduces the Ionic framework with instructions on how to set up the development environment and quickly create and run your first app.
Chapter 2, Adding Ionic Components, walks you through some examples of how to manage pages, states, and the overall navigation within the app.
Chapter 3, Extending Ionic with Angular Building Blocks, takes a deep dive into the Angular components, directives, and the customization of pipes. You will learn how to leverage the Ionic module architecture to create shared services.
Chapter 4, Validating Forms and Making HTTP Requests, explains how to create a complex form with input validation, retrieve data via REST API calls, and integrate with Stripe for online payment.
Chapter 5, Adding Animation, provides instructions on how to embed a video as background, create a physics-based CSS animation, and bind gestures to the animation state.
Chapter 6, User Authentication and Push Notifications, takes a deep dive into registering and authenticating users using Auth0 and sending and receiving push notifications using OneSignal.
Chapter 7, Supporting Device Functionalities Using Ionic Native, explains how to use Ionic Native to access native device functionalities, such as camera, social sharing, InAppBrowser, and map.
Chapter 8, Theming the App, focuses on how to customize the app for different platforms using Sass variables.
Chapter 9, Advanced Topics, teaches how to use advanced ionic features such as lazy loading, deep linking, and localizing ionic apps.
Chapter 10, Publishing the App for Different Platforms, looks into the process of performing the final steps of getting the app published.
In the book, I assume that you have some knowledge of Angular. Most of the time the problem that you will face will be regarding Angular instead of Ionic.
https://angular.io
is your best friend in that case.
If you want to brush up your information about Angular, I would suggest this book by Victor Savkin and Jeff Cross (former Angular team members)
https://www.packtpub.com/application-development/essential-angular
.
Even though you can run most of examples without installing platform SDKs for Android or iOS. I suggest you to do this in the very beginning, in order to test the applications on actual devices. Take a look at these guides:
Android
:
https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#requirements-and-support
iOS
:
https://cordova.apache.org/docs/en/latest/guide/platforms/ios/index.html
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Ionic-Cookbook-Third-Edition. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
<ion-tabs> <ion-tab [root]="tab1Root" tabTitle="One" tabIcon="water"></ion-tab> <ion-tab [root]="tab2Root" tabTitle="Two" tabIcon="leaf"></ion-tab> <ion-tab [root]="tab3Root" tabTitle="Three" tabIcon="flame"></ion-tab> </ion-tabs>
Any command-line input or output is written as follows:
$ ionic start LeftRightMenu sidemenu
$ cd LeftRightMenu
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There's more..., and See also).
To give clear instructions on how to complete a recipe, use these sections as follows:
This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, we will cover the following topics:
Setting up a development environment
Creating a HelloWorld app via the CLI
Creating a HelloWorld app via Ionic Creator
Viewing the app using your web browser
Viewing the app using the Ionic CLI
Viewing the app using Xcode for iOS
Viewing the app using Genymotion for Android
Viewing the app using Ionic View
There are many options for developing mobile applications today. Native applications require a unique implementation for each platform, such as iOS, Android, and Windows phone. It's required in some cases, such as high-performance CPU and GPU processing with lots of memory consumption. Any application that does not need over-the-top graphics and intensive CPU processing could benefit greatly from a cost-effective, write once and run anywhere HTML5 mobile implementation.
For those who choose the HTML5 route, there are many great choices on the market. Some options may be very easy to start, but they could be very hard to scale or could face performance problems. Commercial options are generally expensive for small developers to find product/market fit. The best practice is to think of the users first. There are instances where a simple, responsive website design is the best choice; for example, when a business mainly has fixed content with minimal updating required or the content is better off on the web for SEO purposes.
The Ionic Framework has several advantages over its competitors, as shown:
Ionic is based on Angular, which is a robust framework for application development. You have all the components to structure and create an application built into it.
UI performance is strong because of its usage of the
requestAnimationFrame()
technique.
It offers a beautiful and comprehensive set of default styles, similar to a mobile-focused twitter Bootstrap.
Sass
is available for quick, easy, and effective theme customization.
There have been many significant changes between the launch of AngularJS 1.x and Angular. All of these changes are applicable to Ionic as well. Consider the following examples:
Angular utilizes
TypeScript
, which is a superset of the
ECMAScript 6
(
ES6
) standard, to build your code into JavaScript. This allows developers to leverage TypeScript features such as type checking during the compilation step.
There are no more controllers and directives in AngularJS. Previously, a controller was assigned to a DOM node, while a directive converted a template into a component-like architecture. However, it is very hard to scale and debug large AngularJS 1.x applications due to the misuse of controllers and/or issues with conflicting directives. In Angular, there is only a single concept—that of a component, which eventually has a selector corresponding to an HTML template and a class containing functions.
The
$scope
object no longer exists in Angular because all properties are now defined inside a component. This is actually good news because debugging errors in
$scope
(especially with nested scenarios) is very difficult in AngularJS 1.x.
Finally, Angular offers better performance and supports both ES5 and ES6 standards. You could write Angular in TypeScript, Dart, or just pure JavaScript.
In this chapter, you will work through several HelloWorld examples to Bootstrap your Ionic app. This process will give you a basic skeleton with which you can start building more comprehensive apps. The majority of apps have similar user experiences flow, such as tabs and side menus.
Before you create your first app, your environment must have the required components ready. These components ensure a smooth development, build, and test process. The default Ionic project folder is based on Cordova's. Therefore, you need the Ionic CLI to automatically add the correct platform (that is, iOS, Android, or Windows phone) and build the project. This will ensure all Cordova plugins are included properly. The tool has many options to run your app in the browser or simulator with live reload.
You need to install Ionic and its dependencies to get started. Ionic itself is just a collection of CSS styles, Angular components, and standard Cordova plugins. It's also a command-line tool to help manage all technologies, such as Cordova. The installation process will give you a command line to generate the initial code and build the app.
Ionic uses npm as the installer, which is included when installing Node.js. Please install the latest version of Node.js from https://nodejs.org/en/download/.
You will need to install cordova, ios-sim (an iOS Simulator) and ionic:
$ npm install -g cordova ionic ios-sim
You can install all three components with this single command line instead of issuing three command lines separately. The -g parameter is to install the package globally (not just in the current directory).
For Linux and Mac, you may need to use the sudo command to allow system access, as shown:
$ sudo npm install -g cordova ionic ios-sim
The following are a few common options for an integrated development environment (IDE):
Xcode for iOS
Android Studio for Android
Microsoft Visual Studio Code (VS Code)
JetBrains' WebStorm
Sublime Text (
http://www.sublimetext.com/
) for web development
All of these have a free license. You could code directly in Xcode or Android Studio, but those are somewhat heavy-duty for web apps, especially when you have a lot of windows open and just need something simple to code. Sublime Text is free for non-commercial developers, but you have to purchase a license if you are a commercial developer. Most frontend developers would prefer to use Sublime Text for coding HTML and JavaScript, because it's very lightweight and comes with a well-supported developer community. Sublime Text has been around for a long time and is very user-friendly. However, there are many features in Ionic that make Visual Studio Code very compelling. For example, it has the look and feel of a full IDE without being bulky. You could debug JavaScript directly inside VS Code, as well as getting autocomplete (for example, IntelliSense). The following instructions cover both Sublime Text and VS Code, although the rest of this book will use VS Code.
VS Code works on Mac, Windows, and Linux. Here are the instructions:
Visit
https://code.visualstudio.com.
Download and install for your specific OS
Unzip the downloaded file
Drag the
.app
file into the
Applications
folder and drag it to Mac's Dock
Open Microsoft Visual Studio Code
Press
Ctrl
+
Shift
+
p
to open the command palette
Type the shell command in the command palette
Click on the shell command: Install code command in PATH command to install the script to add Visual Studio Code in your terminal $PATH
Restart Visual Studio Code for this to take effect
Later on, you can just write code (including the dot) directly from the Ionic project folder and VS Code will automatically open that folder as a project.
Note that the following screenshots were taken from a Mac:
If you decide to use Sublime Text, you will need Package Control (
https://packagecontrol.io/installation
), which is similar to a
Plugin Manager
. Since Ionic uses Sass, it's optional to install the Sass Syntax Highlighting package.
Navigate to
Sublime Text
|
Preferences
|
Package Control
.
Go to
Package Control
:
Install Package
. You could also just type the partial command (that is,
inst
) and it will automatically select the right option:
Type
Sass
and the search results will show one option for
TextMate & Sublime Text
. Select that item to install:
There are tons of Sublime Text packages that you may want to use, such as HTML, JSHint, JSLint, Tag, and ColorPicker. You can visit https://sublime.wbond.net/browse/popular for additional needs.
The quickest way to start your app is using the existing templates. Ionic gives you some standard out-of-the-box templates via the command line:
Blank
: This is a simple page with minimal JavaScript code
Tabs
: These are multiple pages with routes. A route URL goes to a tab
Side menu
: This is a template with a left/right menu with the center content area
Super:
This is a template with prebuilt pages and providers, which emphasize the best practices for Ionic app development
To set up the app with a
blank
template from
ionic
, use this command:
$ ionic start HelloWorld_Blank blank
If you replace
blank
with
tabs
, it will create a
tabs
template, as shown:
$ ionic start HelloWorld_Tabs tabs
Similarly, the following command will create an app with a
sidemenu
:
$ ionic start HelloWorld_Sidemenu sidemenu
4. Likewise, the following command will create an app with the super template:
$ ionic start HelloWorld_Super super
Additional guidance for the Ionic CLI is available on the GitHub page: https://github.com/ionic-team/ionic-cli.
This chapter will show you how to quickly start your code base and visualize the result. More details about Angular and its template syntax will be discussed in various chapters of this book, however, the core concepts are as follows:
Component
: Angular is very modular because you could write your code in a file and use an export class to turn it into a component. If you are familiar with AngularJS 1.x, this is similar to a controller and how it binds with a DOM node. A component will have its own private and public properties and methods (that is, functions). To tell whether a class is an Angular component or not, you have to use the
@Component
decorator. This is another new concept in TypeScript since you could enforce characteristics (metadata) on any class so that they behave in a certain way.
Template
: A template is an HTML string or a separate
.html
file that tells AngularJS how to render a component. This concept is very similar to any other frontend and backend framework. However, Angular has its own syntax to allow simple logic on the DOM, such as repeat rendering (
*ngFor
), event binding (
click
), or custom tags (
<my-tag>
).
Directive
: This allows you to manipulate the DOM, since the directive is bound to a DOM object. So,
*ngFor
and
*ngIf
would be examples of directives because they alter the behavior of that DOM.
Service
: This refers to the abstraction to manage models or collections of complex logic besides
get
/
set
required. There is no service decorator, as with a component. So, any class could be a service.
Pipe
: This is mainly used to process an expression in the template and return some data (that is, rounding numbers and adding currency) using the
{{ expression | filter }}
format. For example,
{{amount | currency}}
will return $100 if the amount variable is 100.
Ionic automatically creates a project folder structure that looks as follows:
You will spend most of your time in the /src folder because that's where your application components will be placed. This is very different from Ionic 1.x because the /www folder here is actually compiled by TypeScript. If you build the app for iOS, the Ionic build command line will also create another copy at /platforms/ios/www, which is specifically for Cordova to point to. Another interesting change in Angular is that your app has a root component, which is located at /src/app folder, and all other pages or screens are in /src/pages. Since Angular is component based, each component will come with HTML, CSS, and JS. If you add in more JavaScript modules, you can put them in the /src/assets folder, or a better practice is to use npm install so that it's automatically added in the /node_modules folder. Ionic has completely gotten rid of Grunt and Bower. Everything is simplified into just package.json, where your third-party dependencies will be listed.
There is no need to modify the /platforms or /plugins folder manually unless troubleshooting needs to be done. Otherwise, the Ionic or Cordova CLI will automate the content of these folders.
By default, from the Ionic template, the Angular app name is called MyApp. You will see something like this in app/app.component.ts, which is the root component file for the entire app:
This root component of your app and all content will be injected inside <ion-app></ion-app> of index.html.
Note that if you double-click on the index.html file to open it in the browser, it will show a blank page. This doesn't mean that the app isn't working. The reason for this is that the Angular component of Ionic dynamically loads all the .js files and this behavior requires server access via the http:// protocol. If you open a file locally, the browser automatically treats it as a file protocol (file://), and therefore Angular will not have the ability to load additional .js modules to run the app properly. There are several methods of running the app, which will be discussed later.
Another way to start your app code base is to use Ionic Creator. This is a great interface builder to accelerate your app development with the drag and drop style. You can quickly take the existing components and position them to visualize how it should look in the app via a web-based interface. Most common components, such as buttons, images, and checkboxes are available.
Ionic Creator allows the user to export everything as a project with all .html, .css, and .js files. You should be able to edit content in the /app folder to build on top of the interface.
Ionic Creator requires registration for a free account at https://creator.ionic.io/ to get started.
Create a new project called
myApp
:
Validate, to ensure that you see the following screen:
The center area is your app interface. The left side gives you a list of pages. Each page is a single route. You also have access to a number of UI components that you would normally have to code by hand in an HTML file. The panel on the right shows the properties of any selected component.
You're free to do whatever you need to do here by dropping components to the center screen. If you need to create a new page, you have to click on the
Add Page
in the
Pages
panel. Each page is represented as a link, which is basically a route in Angular UI-Router's definition. To navigate to another page (for example, after clicking a button), you can just change the link property and point to that page.
There is an edit button on top, where you can toggle back and forth between the edit mode and preview mode. It's very useful to see how your app will look and behave.
Once completed, click the export button at the top of the navigation bar. You have the following four options:
Use the Ionic CLI tool to get the code
Download the project as a ZIP file
Export it to native code (similar to PhoneGap Build), as shown:
Export it to the preview mode using the Creator app
The best way to learn Ionic Creator is to play with it.
To switch to the preview mode, where you can see the UI in a device simulator, click on the switch button in the top right to enable Test, as illustrated:
In this mode, you should be able to interact with the components in the web browser as if they're actually deployed on the device.
If you break something, it's very simple to start a new project. It's a great tool to use for prototyping and to get the initial template or project scaffolding. You should continue coding in your regular IDE for the rest of the app. Ionic Creator doesn't do everything for you yet. For example, if you want to access specific Cordova plugin features, you have to write that code separately.
Also, if you want to tweak the interface outside of what is allowed within Ionic Creator, it will also require specific modifications to the .html and .css files.
In order to run the web app, you need to turn your /www folder into a web server. Again, there are many methods to do this and people tend to stick with one or two ways to keep things simple. A few other options are unreliable, such as Sublime Text's live watch package or a static page generator (for example, the Jekyll and Middleman apps). They are slow to detect changes and may freeze your IDE, so won't be mentioned here.
The recommended method is to use the Ionic serve command line. It basically launches an HTTP server so that you can open your app in a desktop browser.
First, you need to be in the project folder. Let's assume that it is the side menu
HelloWorld
:
$ cd HelloWorld_Sidemenu
From there, just issue the simple command line, as shown:
$ ionic serve
That's it! There's no need to go into the /www folder or figure out which port to use. The command line will provide the following options while the web server is running:
The most common option to use here is Ctrl + C to quit when you are done.
There are additional steps to view the app with the correct device resolution:
Install Google Chrome if it's not already on your computer.
Open the link (for example,
http://localhost:8100/
) from Ionic serve in Google Chrome.
Turn on Developer Tools. For example, in Mac's Google Chrome, navigate to
View
|
Developer
|
DeveloperTools
:
Click on the small mobile icon in the Chrome Developer Tools area, as illustrated:
There will be a long list of devices to pick from, as shown:
After selecting a device, you need to refresh the page to ensure that the UI is updated. Chrome should give you the exact view resolution of the device.
Most developers would prefer to use this method to code, as you can debug the app using Chrome Developer Tools. It works exactly like any other web application. You can create breakpoints or output variables to the console.
Note that Ionic serve is actually watching everything under the /src folder and transpiring the TypeScript code into JavaScript under /www on the fly. This makes sense because there is no need for the system to scan through every single file when the probability of it changing is very small.
While the web server is running, you can go back to the IDE and continue coding. For example, let's open page1.html or any other template file and change the first line to this:
<ion-view view-title="Updated Playlists">
Go back to the web browser where Ionic opened the new page; the app interface will change the title bar right away without requiring you to refresh the browser. This is a very nice feature when there is a lot of back and forth between code changes and instantly checking how it works or looks in the app.
So far, you have been testing the web app portion of Ionic. Most of the time, you will need to actually run the app on a physical device or at least an emulator to see how the app behaves and whether all native features work.
You will need to have the emulator installed. iOS emulator comes when you do npm install, -g ios-sim, and the Android emulator comes with Android Studio. To test the app on a physical device, you must connect the device to your computer via a USB connection.
Add the specific platform (such as iOS) and build the app using the following command line:
$ ionic cordova platform add ios
$ ionic cordova build ios
Note that you need to add the platforms to build the app. However, if you use the standard template from the Ionic CLI, it should already have the iOS platform included. To build and run for Android, you can replace iOS with Android.
To emulate the app using the
ios
emulator, use the following command line:
$ ionic cordova emulate ios
To run the app on the actual physical iPhone device, use the command line as shown:
$ ionic cordova run ios --device
You could run the app using Xcode (in Mac) as well.
