Ionic 4 (Look Inside)
Ionic 4 (Look Inside)
Ionic 4 (Look Inside)
www.dunddverlag.de
ISBN (Print): 978-3-945102-52-7
Preface
How do I get to write this book? ...............................................................................................1
I would like to thank ........................................................................................................................... 2
1 Introduction
1.1 The idea behind Ionic................................................................................................................. 5
1.2 Installations..................................................................................................................................... 15
1.3 How to read this book........................................................................................................... 19
1.4 The book‘s website................................................................................................................... 20
1.5 Our „BoB Tours“ app.............................................................................................................. 21
Summary................................................................................................................................................. 24
2 Angular Essentials
2.1 What is Angular?....................................................................................................................... 25
2.2 Components................................................................................................................................. 27
2.3 Lifecycle Hooks........................................................................................................................... 30
2.4 Dependency Injection............................................................................................................. 34
2.5 Routing and Lazy Loading................................................................................................... 36
2.6 Content Projection.................................................................................................................... 39
2.7 *ngFor.............................................................................................................................................. 40
2.8 Pipes.................................................................................................................................................. 41
2.9 Promises......................................................................................................................................... 44
2.10 Observables.............................................................................................................................. 46
2.11 Async / Await............................................................................................................................. 51
Summary................................................................................................................................................. 54
I
4 Navigation
4.1 Have a plan.................................................................................................................................. 71
4.2 Generate pages.......................................................................................................................... 73
4.3 Routing............................................................................................................................................. 80
4.4 Extract Data from Routes with ActivatedRoute.......................................................83
4.5 Pro Tip - Install the Augury Chrome Plugin..............................................................88
Summary................................................................................................................................................. 89
6 UI Components
6.1 Introduction................................................................................................................................ 145
6.2 Action Sheet.............................................................................................................................. 147
6.3 Alert................................................................................................................................................ 154
6.4 Badge............................................................................................................................................ 159
6.5 Button........................................................................................................................................... 165
6.6 Card............................................................................................................................................... 166
6.7 Checkbox.................................................................................................................................... 171
6.8 Chip................................................................................................................................................ 176
6.9 Date & Time Pickers............................................................................................................ 179
6.10 Floating Action Button..................................................................................................... 186
6.11 Grid............................................................................................................................................... 190
6.12 Icons............................................................................................................................................ 194
6.13 Images....................................................................................................................................... 199
6.14 Input............................................................................................................................................ 202
6.15 List................................................................................................................................................ 206
6.16 Menu.......................................................................................................................................... 213
II
6.17 Modal......................................................................................................................................... 216
6.18 Popover.................................................................................................................................... 227
6.19 Progress Indicators............................................................................................................. 234
6.20 Radio.......................................................................................................................................... 238
6.21 Range......................................................................................................................................... 244
6.22 Reorder..................................................................................................................................... 254
6.23 Searchbar................................................................................................................................. 259
6.24 Segment................................................................................................................................... 263
6.25 Select.......................................................................................................................................... 273
6.26 Slides ......................................................................................................................................... 277
6.27 Toast............................................................................................................................................ 287
6.28 Toggle......................................................................................................................................... 290
6.29 Toolbar....................................................................................................................................... 295
Summary.............................................................................................................................................. 298
7 Form validation
7.1 Introduction................................................................................................................................ 299
7.2 Defining our form requirements....................................................................................300
7.3 Implementation........................................................................................................................ 302
Summary.............................................................................................................................................. 321
III
9 Ionic Native
9.1 Introduction .............................................................................................................................. 385
9.2 Geolocation................................................................................................................................ 387
9.3 A map for our app............................................................................................................... 393
9.4 Native Plugins in browsers............................................................................................... 415
Summary.............................................................................................................................................. 416
IV
Bonus: Ionic and other frameworks
B1. Ionic without any framework........................................................................................... 557
B2. Ionic and Capacitor............................................................................................................... 561
B3. Ionic and React........................................................................................................................ 569
B4. Ionic and Vue............................................................................................................................ 590
Summary.............................................................................................................................................. 626
V
VI
Preface
Preface
How do I get to write this book?
“Ionic 4+ - Creating awesome apps for Android, iOS, Desktop and Web” is my
second book about the excellent Ionic framework for developing mobile apps. My
own search for specialized literature on this topic was sobering: the few things there
are to be found in the book trade are outdated. That's when I realized: the book
I'm looking for has yet to be written!
Just like my first book "Ionic 3 - Developing attractive Apps for Android, iOS and
Windows", “Ionic 4+” addresses new or emerging software developers who previ-
ously had little or nothing to do with programming apps or worked with other
tools and frameworks and want to build really cool apps in a simple way. If you
feel addressed, this book is for you!
The book spans from the idea of the popular app framework Ionic and its installa-
tion to the realization of a complete app including its publication in Google Play
and Apple's App Store. It offers you a comprehensive introduction to Ionic. With
in-depth background knowledge, for example, on Angular, Cordova or JavaScript,
I'll hold myself back; there is already good literature about it. A small exception is
the second chapter "Angular Essentials", in which I briefly describe the essential
concepts and structures of Angular 7. The one who would like to know more, I'll
offer further links in suitable places.
For each chapter I dedicate an own aspect of Ionic and gradually add new func-
tionalities to an initially simple app called "BoB Tours". If you accompany me, at the
end of this book, you not only learned to know and use the most important fea-
tures of Ionic, but also understood how it works in context. With that you finally
have the necessary knowledge to be able to develop your own awesome apps
with Ionic.
If you find a chapter less exciting or want to skip for any other reason, you can
download the source code of a chapter from the book's website (see "The book's
website" on page 20) and continue working on the following chapter.
1
Ionic 4+
... Simon Grimm for his great project "Ionic Academy" (https://ionicacademy.com),
whose visit I highly recommend to any new Ionite.
... Paul Halliday, Josh Morony, Max Schwarzmüller, Jorge Vegara, Sani Yusuf and all
the other passionate authors of excellent Ionic tutorials.
... the team of the GFU Cyrus AG in Cologne, Germany, which was infected by my
enthusiasm for Ionic and spontaneously integrated me into their seminar program
with this topic.
... my dear friends Bernd Schnur and Harald Sichert for good advice and careful
editing of my first book. It's a pity you didn't have time for this second book... but I
know: You are always busy and, of course, the summer in Germany was too fan-
tastic.
… the readers of my first book for the precious feedback that motivated me to
stay tuned.
... you and all other readers of this second book. Feel free to give me precious
feedback this time, too.
... finally and emphatically with my loved ones for their patience and consideration
when I worked hours and hours on this book and for their amazing leniency, when
I talked about Ionic, Apps & Co. no less often and always long lectured. What they
have left behind them, you as a reader can now look forward to ;-)
Andreas Dormann
2
Preface
3
Ionic 4+
4
1 Introduction
1 Introduction
1.1 The idea behind Ionic
The creators of Ionic didn't reinvent the wheel. The made it even rounder!
The Ionic framework with its functions and components gives us a clear direction to
a straightforward app development for Android, iOS and the web – and – if you
like it – for the desktop and Windows 10 Universal, too. Ionic itself takes mainly
established and very well proven frameworks and forges it together to a powerful
Software Development Kit (SDK).
Let me shortly introduce the most important frameworks and modules under the
hood of Ionic:
Angular
Angular (formerly known as AngularJS) is a JavaScript framework for creating sin-
gle page web applications. It is developed by a community of individuals and
companies, led by Google, and published as open source software.
Angular has data binding as an automatic way of updating the view, controllers to
manage the DOM, directives to establish new HTML syntax, reusable components,
form validation and much more.
Ionic has a specific @ionic/angular package that helps with integration with Angu-
lar. In the chapter "Angular Essentials" (starting on page 25) I describe the most
important concepts of this powerful framework.
More about Angular you can find here:
5
Ionic 4+
https://angular.io
App-Scripts
When ionic serve or ionic cordova run are invoked, it ultimately calls Node
Package Manager (npm) scripts. These npm scripts call the @ionic/app-scripts li-
brary to execute the build process.
Out of the box, Ionic starters have been preconfigured with great defaults for
building fast apps, including:
6
���������&������
I�������&�����0(���������&�����7��������-
�������-::����&�%���:�����0����:�����0���0�������
���������7��
�&�����7�8����������� �����������'�����0�����7��0���7�8����������0$�������(���:�((
����%�6�������&������������������E����((��& �����&�$�����$� ������� ������������
�&������������$����%�9��L����'���� ��3��������8��� �%�
Q�&�$����-
����������
������������������
������������������������
���� �����������������
����������� ������������������������������� !����������"�
#
�&�����7�8���������������������������������-
����������
����������������������
������������������
����� ��������������������������
���������������������������
������������������������
����� ������ �����������������
����������$� �����������������
������������ �����������������
������������ �����������������
����������� ����� �������������������������%�������
������������������������%����������%���� !���"����������""�
����������� ����� ��������������������������� !����������"�
����������� ���������������������������� !����������"�
����������� ������������������������������� !����������"�
#
I�������&���&�����7�8�����&�����7��������-
.
��������
�������-::����&�%���:�������:�&�����7�8��U���$����
������� �$�����
#��� �L��� ��&�������� ����������� �7�����3����M�'�(��������$� ���������&��7�����%
���������7������ ����7��������&���� ���&�������������������"��������� ���7���
M�'�(����������������M�'�(�����%�������������&��M�'�(�����"���� �E�����"�����'�������
�����������$����������������E���$���L�� �7�%����� �������3�������8"�'����� ����7��0
���������������"�����$��������&���������M�'�(���������7� �%
/
���������&������
������
������������'��*7����� ��+����#��,������������������������7����������$��
������ ������*=6I92"� �((1� ���� M�'�(�����,����� �:������� ����� 7�������� � ��0
7����%�������� ���$��������&���7��(("�=6I9"�����M�'�(���������������������&���
����� ��7�����7�������'���%�
����8����������7���&�����7�=6I9�����M�'�(���������$��3�$����������'���%�6������& �0
��� � ��� �������� � ��� � ������" � ������� � ���� � ���� � ��� � ������� � ��& � � ����'� � ���� �
��� ��������*����&���� � ���&��������������������'���B���'��$�����������7������ �� 0
7���L������'��H��7����$��3,������&�� ��B��0������*����&����������������C&���B��
����"��&���������3�������������7����������&�����������'����������������'����'���
�+��,%�
����� � ���� � &�� � ����� � ��� � � &���� � �� � ���'��� � ����0����$��� � 7&������� ����� � �3�
������"����� ��������������� �������%��������� �������&�����������7������'��� &����
������)���'�%����������������������������������������N������)���'�N�*����������������
1/2,%
I�������&�������'����&�����7��������-
�������-::�����'�%������%���
�������-::�����7����$��3%���:����:����'�:
�
Ionic 4+
Git
Git is a free and open source distributed version control system for managing
code. It allows development teams to contribute code to the same project without
causing code conflicts.
Git is easy to learn and has a tiny footprint with fast performance. It outclasses
SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap
local branching, convenient staging areas, and multiple workflows.
Git works directly with Ionic Appflow (see “12.9 Ionic Appflow“ on page 548).
Appflow uses your code base as the source of truth for Deploy and Package
builds. In order for Appflow to access your code, you can choose to integrate di-
rectly using a hosting service like Github or Bitbucket, or you can push your code
directly to Appflow.
More about Git and related topics you can find here:
https://git-scm.com
https://git-scm.com/book/en/v2
https://github.com
https://bitbucket.org
10
���������&������
����59�
)���%C��������&��������'��������������� �$��M�'�(������������$�����������������'��0
����%����������������������&����7���$������'����"����������7����&��������&� ����'� 0
�������� �"��&�����������������9�%
!����������+������% ����������)�����"��
������ ����,����-''���
����*.�������/���*��*�����!���*
��#"�
������ �����*,�����0���*"�
����������"�
#"��������&'''"�
I�������&��)���%C�������� ��������������&�����7��������-
�������-::����C�%���
� �����-::$$$%C���������%���:�����������0��0�����0��� �������0$���0�0
����C�0���3���:
��
Ionic 4+
Stencil (new)
Stencil is a Web Component compiler built by the Ionic Framework team to help
build faster, more capable components that work across all major frameworks.
Web components are a set of web platform APIs that allow you to create new cus-
tom, reusable, encapsulated HTML tags to use in web pages and web apps. They
are based on existing web standards.
Stencil combines the concepts of popular frameworks into a simple build-time tool.
https://stenciljs.com
https://github.com/ionic-team/stencil
12
1 Introduction
TypeScript
TypeScript is a superset of JavaScript, which means it gives you JavaScript, along
with a number of extra features such as type declarations and interfaces. Although
Ionic is built with TypeScript, using it to build an Ionic app is completely optional -
but recommended.
The first publicly available version of TypeScript was released in 2012 after two
years of development by Microsoft in version 0.8. Shortly after the language was
announced, it was praised by Miguel de Icaza. However, he complained that there
were no other development environments apart from Microsoft Visual Studio,
which wasn't available for Linux and MacOS in 2013. Since 2013 there was plug-
in support for Eclipse. Meanwhile, a variety of text editors and development envi-
ronments support TypeScript. These include Emacs, vim, Sublime Text, WebStorm,
Atom and Microsoft's own Visual Studio Code editor. The latter I'll use in this book
to develop Ionic apps.
TypeScript doesn't render JavaScript a static typed language, but allows strong typ-
ing. With this, variables and methods can be typed, whereupon certain errors can
be detected even at compile time.
The basic types in TypeScript are: Any, Array, Boolean, Enum, Never, Null,
Number, Object, String, Tuple, Undefined, Void.
https://www.typescriptlang.org
http://www.typescriptlang.org/docs/handbook/basic-types.html
13
��������
<�����2
B�����3��&�� ������������M�'�(���������& �������������������%�����������&������
����������� ������& ��� ��N��&�3�N������������ �� ������$����������%�B�����3����
���&���������3�������7� �������������������������&�� ����������������7� �"���
�����������%
I�������&��B�����3���&�����7��������-
�������-::$�����3%C�%���
��
���������&������
�5�� �������������
�����!���$
<������7�� ���3���&����������� ����� ������'��������7�)���%C��7���
�������-::����C�%���
)��������&�� ���$�������"��������3������������7���M�'�(�����%
�2
��������
������ =�
)�$�$������� ������������������0 ����&�� ����*�9�,%�����&�������&��$�������&�����7
��'���� �������� ��������������������������'� ����&����� ��������%������ ����������
�9��� ��� ��$������$-
9����������������������
���������&�����7���������3�$��$� ��������3��$������������������������������7
�����������9�%�6����'����&�����'��'��$������'����"���&���������������7� �$�����7���
����� ���������9���������������� -
9���������!���
� �����-::�����7����$��3%���:����:� �
�F
���������&������
� �����-::����%'��&� ��&���%���:
��L�������������������'� �������4�'���������*��4,���&��������������3%�6�����������4
� �������'��� �3������A���K�I������7�����&� �(�&���"����������4� �������"��7���&���"
�����L���$����$�������(�&����*�����-::�����7����$��3%���:��&���,%�
(����������� &���������������8� ��������������������3���������������(�"���$�'��"��
�����������������&�� ���&����(���7���&�$��������������7� �$�������������������
��������3������'����*'��&� ,���'�������%
�.
��������
8������ ���$�
<�����'� ��������&������������$����'������$������&�$���%�!&����������������
&���#��� ��������%������&� �0���<���������/�����$� ���'��&���������&������$�� �
��'� �����"����&��������������������������� ��������%
Q�&���������� ����7���
�������-::$$$%���� �%���:������
���&���������'� �����'�������7���
�������-::$$$%���� �%���:������:��'
�/
���������&������
�5�� 3�1�����������������2
6����������7���������3����� ����&������������� ���������� ���@!�!�6�&��A%����������
�����������1�*@6���7��������A"������������������22,������������������������*@!&� �"
��� ��������&� ���A"����������������� �2�.,%�����'��������������&L � �������$���
������$����������������7&������� ���������������&��� ���L������� �$�� ����� �������%�
6���������&��������������7���������3�*@����������������7����$��3�A"������������
�����22.,����7����������7���&"�$���$������� ��3�������������������&��%�(������������
��&�����L�����7���������&������& ��%�6���������������������� �������'��� �3��4 ������"
CX&���"�D����������&�%������������������L ���3���� ��3��������$�� ������������& ��
�������$���&���$�������7�������������7����$��3��7������������$���������%
��
Ionic 4+
If it happens that you read my book in a few months, install the latest version of
Ionic and notice at some point that the code used here for some reason doesn't
work, take a look at the forum of the website. If necessary, updated hints are given
for each chapter. Otherwise, don't be afraid to post a question in the forum. The
reader community and I will do our best to answer as soon as possible.
Here are web address and code to my book's website:
https://ionic.andreas-dormann.de/
Scan me
20
1 Introduction
Our app can be characterized as follows: "BoB Tours" is the app of an imaginary
tourism company called "Best of Bonn Tours GmbH", in short: "BoB Tours", that of-
fers city tours, biking, hiking and segway trips around my beautiful home of Bonn.
In the app, the tour offer can be searched for regions (e.g., "Bonn City" or "Bonn's
Surrounding Areas") and tour types (e.g., “Round Trips” or "Segway Tours") as well
as for a price range. If you have found an interesting tour, you can view their de-
tails together with a photo and save them as a favorite.
21
Ionic 4+
The starting point and the route from the current location to the starting point of
each tour can be displayed in a map. Finally, you can formulate and send a book-
ing request directly to the tourism company from the app. Of course the form will
be validated.
Our app should make a good impression on a smartphone, in the browser and on
a tablet as well. Therefore, we will also turn to the aspect of "responsibility".
In the user settings, you can finally switch between different color designs.
You see, the whole thing is already a small real life app. In doing so, we will en -
counter a number of typical programming situations, as in the real life of an app
developer.
22
���������&������
��������� �"�������������������7������������7����������7�������������������&���77������
������&���%��%�������������� ��������������������������$����(� �����(������
�������8�� ������&���&���J
=������&�����$������������'��������7�N!�!�6�&��N-
�������-::�����%�������0�������%��:����
�1
Ionic 4+
Summary
In this chapter, you got to know the idea behind Ionic. You now know that Ionic has
many specialized single frameworks under its hood.
You also did all the installations necessary to work with Ionic: Node and npm, Ionic
CLI, Microsoft Visual Studio Code and Google Chrome with its Dev Tools.
I finally introduced you to the book website and our app "Bob Tours".
24
2 Angular Essentials
2 Angular Essentials
2.1 What is Angular?
Preliminary remarks
Client-side programming has become extremely complex in recent times. The re-
quirements for a web application are now just as high as for a desktop application
- if not higher. The desire for a framework that enables the developer to cover all
these requirements on the web is thus getting bigger.
It should not go unmentioned that Ionic 4 also cooperates with other frameworks. I
have dedicated this topic to the bonus chapter “Ionic and other frameworks” (start-
ing on page 557).
25
Ionic 4+
Angular makes it possible to communicate with components, feed them with data
and receive events from components; it makes components reusable and more
isolated. For example, the flexibility to separately develop the view as HTML allows
different teams to work on logic, architecture, and design.
In order to achieve the greatest possible flexibility and to be broadly positioned,
Angular draws on further projects and their functionality, such as RxJS. The integra-
tion of third-party libraries is therefore simple and simple, which means you can
extend your application to almost any JavaScript library and use its flexibility.
This allows you to create complete applications that are bigger and more powerful
than a "normal" website: A web application that has the same rights and obligations
(architecture, testability, etc.) as an application in a familiar language, such as the
desktop.
In this chapter I describe the most important concepts and structures of Angular,
which can be useful for you in the realization of your Ionic Apps.
26
2 Angular Essentials
2.2 Components
With Angular, there is no direct manipulation of the HTML-DOM, but a separation
according to the model-view-controller (MVC) pattern: In the view, the developer
defines so-called templates that connect static HTML tags with dynamic contents
from the controller. This mix allows the framework through custom HTML syntax
elements ("directives").
In the template for the tour list in Listing 2 you can see a custom tag again with
<TourDetails>. This is a child component that interacts with the parent compo-
nent through properties and events. Using the @Input() and @Output()
decorators, the developer must clearly define which properties and events are ac-
cessible to other components. For event communication Angular offers its own
event emitter.
A component triggers various events throughout its lifecycle that the developer can
hook into. Listing 1 shows this with the example of the event OnInit, which from
the point of view of TypeScript is a class that, like all other types, has to be integrat-
ed with import {OnInit, ...} from '@angular/core'. Other events are related
to data binding (ngOnChanges, ngDoCheck).
27
Ionic 4+
@Component({
selector: 'TourList',
templateUrl: 'App/TourList/TourList.html',
providers: [BookingService]
})
export class TourList implements OnInit {
status: string;
tours: Tour[];
ngOnInit() {
this.bookingService.getAll(data => { // Callback
this.tours = this.bookingService.tours;
this.status = this.tours.length + " tours booked.";
});
}
Delete(tour: Tour) {
this.bookingService.delete(tour); // Call service
this.status = `Tour ${tour.ID} deleted!`;
}
Change(tour: Tour) {
let link = ['/edit', tour.ID];
this.router.navigate(link);
}
28
2 Angular Essentials
Don't worry if this seems very abstract to you. From the next chapter we will cre-
ate many components (pages) ourselves. And with the help of Ionic, the whole
thing will be very easy for you.
Further informations about this topic you can find in the official Angular documen-
tation:
https://angular.io/guide/architecture-components
29
��������
�5�� =����)����3��2�
��������&�����������& ���9�7���� ��=��3�%�6���L��$��������3�������������������� �� 0
� ���������������-
� &����������������77�������������������& �������������*����A�%������������K"�
���������7����������.,����������&���7������������������������������������%
� 3��$���$�������3������������������������&����&���$������%
� 3��$��������������$�����������77������������������������$������������������
�����%
������������������& ��������� �7���� �"�����������7���77�������������������������
����&���7����A������ �� ������K% �B������7��� ����E�� �&��� '���$���������� ��77�����
�����������������������7���������� ��7��&����� �������%�6���������"�$��������������0
��7���������������&������������� ��������������� ����&�����������7������� �7���� �
������%�6������������������� ��������%
6������3�������8��&�����������������-
1�
2 Angular Essentials
We distinguish between hooks for the component itself (red and blue) and hooks
for their children (green).
ngOnChanges
is invoked every time there is a change in one of the input properties of a compo-
nent.
ngOnInit
is invoked when a component has been initialized. This hook is only called once af-
ter the first ngOnChanges
ngDoCheck
is invoked when the change detector of a component is invoked. It allows us to im-
plement our own change detection algorithm for a component.
ngOnDestroy
This method will be invoked just before Angular destroys a component. Use this
hook to unsubscribe Observables (see “2.10 Observables”, starting from page 46)
and detach event handlers to avoid memory leaks.
is invoked after Angular performs any Projection (see “2.6 Content Projection” on
page 39) into a components view.
ngAfterContentChecked
is invoked each time the content of the given component has been checked by
the change detection mechanism of Angular.
31
Ionic 4+
ngAfterViewInit
is invoked when a component’s view has been fully initialized.
ngAfterViewChecked
is invoked each time the view of the given component has been checked by the
change detection mechanism of Angular.
Code example
In this code I show a typical use of the constructor and ngOnInit hook. Both will
be used regularly throughout this book. They're Angular's bread and butter hooks.
import { Component } from '@angular/core';
@Component({
selector: 'actors-data',
templateUrl: 'actors-data.html',
})
export class ActorsData {
myStar;
constructor() {
console.log('constructor – My star is $(this.myStar)');
myStar = 'Julia Roberts';
}
ngOnInit() {
console.log('ngOnInit – My star is $(this.myStar)');
}
32
2 Angular Essentials
At the constructor's console log output the property myStar is undefined. The val-
ue is assigned after the console statement. By the time the ngOnInit hook is called
we can see that the property myStar is now set to the given value.
More detailed information about Lifecycle Hooks you can find here:
https://angular.io/guide/lifecycle-hooks
https://ionicframework.com/docs/lifecycle/angular
33
Ionic 4+
class Environment
{
Client c = new Client();
c.Process();
}
class Client
{
public void Operation()
{
Service d = new Service();
d.Action();
}
}
class Service
{
public void Action()
{
...
}
}
34
2 Angular Essentials
class Environment
{
Client c = new Client(new Service());
c.Process();
}
class Client
{
Service d;
class Service
{
public void Action()
{
...
}
}
Further informations about this topic you can find in the official Angular documen-
tation:
https://angular.io/guide/dependency-injection
35
Ionic 4+
Routes
A route simply defines an URL path and a component to display it's content.
There are three main types of routes that you will use frequently:
// Redirect
{ path: 'here', redirectTo: 'there', pathMatch: 'full' }
];
src/app/app-routing.module.ts
The root configuration for an Ionic application router lives in the src/app/ap-
p-routing.module.ts file. Here you define your routes. For pages that you
generate with the Ionic CLI ( ionic generate page...) all corresponding routes
are defined automatically. For example see the route for a page named Fa-
vorites:
{
path: 'favorites',
loadChildren: './pages/favorites/favorites.module#FavoritesPageModule'
}
36
2 Angular Essentials
many components). The basic idea of lazy loading is that it breaks your application
down into smaller chunks, and only loads what is necessary at the time. When
your application is first loaded, only the components that are necessary to display
the first screen need to be loaded. This is especially beneficial for Progressive Web
Apps where page load times are critical. This magic is made possible with
Webpack Code Splitting.
With lazy loading, your application can boot much faster because it doesn’t need to
load much – you could have a huge application, with 50 pages, but it could still
load just as fast as an application with just 2 pages.
A lazy loaded route renders the FavoritesPageModule where the so called out-
let is defined in the HTML in the app.component.html:
<ion-router-outlet></ion-router-outlet>
When you navigate to the /favorites path in the browser, it will render the spe-
cific component in the HTML outlet.
Ionic's own router outlet implementation <ion-router-outlet> (basically, you just
plop the router outlet wherever you want the component for the active route to
be displayed) is mostly the same as Angular’s <router-outlet> except that it will
automatically apply the screen transition animations with a “direction” (e.g. a for-
ward navigation will animate the new screen in from the right).
ActivatedRoute
Angular has an ActivatedRoute to bring data from one page to another. In other
words: an ActivatedRoute contains the information about a route associated with
a component (page) loaded in an outlet.
Example: Data is sent from a calling page e.g. via HTML like
[routerLink]="['/target', data]"
@Component({
selector: 'app-target',
37
Ionic 4+
templateUrl: './target.page.html',
styleUrls: ['./target.page.scss'],
})
export class TargetPage implements OnInit {
incoming_data = null;
ngOnInit() {
this.incoming_data = this.activatedRoute.snapshot.params;
}
38
������& ���4������� ��
�5"� ����������9������
6�����������$���������� ����������������������������������������������������
����&�����������+��C������%�B������������+��C������"���&��&����������������������
����'��$����� ���"���� ����������&� ���&� ��������-�����+���##%
���=6I9���&�����$����-
?!K;�������##?�!K;
?!-;A��%���������������������+���##?�!-;
Q�&�$�������3��$���������&������������>�6��������-
1�
��������
�5%� F��&��
5���'�����7����&�������& ����������'�������J��%���L����A��������K��������'�������� ��
��&����������������&�������������7���C����%�
<&��������7�������������&���������������&�����7��������������& ������&���������-
�������-::���& ��%��:�&���:���� �����0����
��
������& ���4������� ��
�5'� �����
���& ������������� ������������������7���������:���7�����������������5I���7���
����������*7����������"�7����8��� �,%�57���"�$������������������&�����8��������"���&
���L��$����������� ������������$�����������������������"��'����������'��$%��������
$����'�������������C���� �3������-
���������.���������#�%����*���� ��������*�
�.����������
������������*����������*�
����������7����*�����������!���*�
#"
�������������1����<�����
����� ( �
����������*> ����=������*�
��������!������� �<����KRST��K'��-U"�
��#
�������=6I9�7� ��$��&�����������+��C�������*����A�%F���������+��C������K��������
1�,�������� �����������-
?���;
��?!K;������������##?�!K;
��?!-;������������!���##?�!-;
?����;
(���� � ��� � ������� � +��C������ � �� � ���� � ���� � &��� � ��� � ��+������, � ������ � �� ����
��������!��� �������������������& ���7�����������'��$"�����7� �$������������������
����H�-
=�$�'��"��&��&��������������������������������&�����������E����������������7����
$��3%�(��$��C&���$����������$���������������������������7�����%���������������0
��
Ionic 4+
plement this formatting as elegantly as possible, Angular offers the possibility to use
pipes for this purpose. You use a kind of filter for the Content Projection, which
then delivers the result. For this we need a new TypeScript class, which is declared
as a pipe with a decorator:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'birthdayFormatPipe'
})
export class BirthdayFormatPipe implements PipeTransform {
Now we have to make the pipe known with our ActorData component module:
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ActorData } from './actor-data';
import { BirthdayFormatPipe }
from './../birthday-format.pipe';
@NgModule({
imports: [
...
],
declarations: [ActorData, BirthdayFormatPipe]
})
export class ActorDataModule {}
42
������& ���4������� ��
)�$�$����'�����&����&��������������=6I9�7� �%�6��&���������"�$�������������0
�� �����������������* ,-
?���;
��?!K;������������##?�!K;
��?!-;������������!����M�����!���J�����N���##?�!-;
?����;
Q�&�$�������3��$���������&�������>�6��������-
�������-::���& ��%��:�&���:�����
�1
Ionic 4+
2.9 Promises
Let's create a simple example with setTimeout to simulate a real Promise (like an
asynchronous database call):
function asyncWriteFanMailToJuliaRoberts() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Mail sent!");
if (error) {
reject();
} else {
resolve();
}
}, 1000);
});
return promise;
}
Resolve a Promise
But how do we respond to a resolve or a reject? To do this, each Promise ob-
ject has a then function, which means something like: If the asynchrony is finished
or the promise has been resolved (by resolve or reject), then execute. For this
reason, promises are also often called thenables.
This then function can handle two callback functions. The first for the success and
the second for the case of error.
44
2 Angular Essentials
Without the need to understand the code of the function getTours(), you imme-
diately realize that getTours() is a Promise function, right? The little word then
tells it. Once getTours() asynchronously and successfully returns data, some more
functions (inside the curly brackets) are executed here. All these inner functions can
rely on getTours() keeping its promise and delivering valid data.
Further informations about Promises you can find here:
https://codecraft.tv/courses/angular/es6-typescript/promises/
45
Ionic 4+
2.10 Observables
An observable is an object that emits events (or notifications). An observer is an
object that listens for these events, and does something when an event is received.
Together, they create a pattern that can be used for programming asynchronously.
The principle is very similar to the Observer pattern and is called Reactive Pro-
gramming. Angular uses the observables of the ReactiveX architecture as a basis.
Through Microsoft's Microsoft Reactive Extensions, there is a very good implemen-
tation in JavaScript and other languages - called RxJS for short.
Let's look at a complete example of how observables in Angular (and Ionic) can be
used. In the following, the individual sections and functions of the following source
code are explained in more detail.
@Injectable({
providedIn: 'root'
})
export class ActorsService {
actors = [{
id: 1,
name: 'Julia Roberts',
birthday: new Date('1967-10-28')
},
46
2 Angular Essentials
{
id: 2,
name: 'Richard Gere',
birthday: new Date('1949-08-31')
},
{
id: 3,
name: 'Hector Elizondo',
birthday: new Date('1936-12-22')
}];
constructor() { }
// Create an Observable
public getActors(): any {
const actorsObservable = new Observable(observer => {
setTimeout(() => {
observer.next(this.actors);
}, 1000);
});
return actorsObservable;
}
@Component({
selector: 'actors-data',
templateUrl: 'actors-data.html',
})
export class ActorsData {
actors = [];
47
Ionic 4+
ngOnInit() {
const actorsObservable = this.actorsService.getActors();
// Define a Subscriber
actorsObservable.subscribe((actorsData) => {
this.actors = actorsData;
});
}
Explanation to Listing 1:
In a service (actors.service.ts) there is an array of actors (this data could also
come from a database):
actors = [{
id: 1,
name: 'Julia Roberts',
birthday: new Date('1967-10-28')
},
{
id: 2,
name: 'Richard Gere',
birthday: new Date('1949-08-31')
},
{
id: 3,
name: 'Hector Elizondo',
48
2 Angular Essentials
The Observable calls the next method of its observer object to emit data
(this.actors). To be able to use an Observable, Observable is to be imported
from the ReactiveX library (RxJS):
import { Observable } from 'rxjs';
Explanation to Listing 2:
In ngOnInit the service is called and a subscriber is defined who writes the data
output by the service to the actor array:
ngOnInit() {
const actorsObservable = this.actorsService.getActors();
actorsObservable.subscribe((actorsData) => {
this.actors = actorsData;
});
}
49
��������
�7�������������=��������0
�������=6I9�7� �"�����������������������'������G ��J�� ����*����A�%. �G��<��K���
�������,����������'��$%
@�����������������������1����
Q�&�$��L��� $�����������5����'�� �����&��� 7%�I����M�'�(������ ������������'���
������7&������� ����'���5����'�� ��%�������������������������'���7����5����'�� ����
!��������"" � $���� � �� � ���'���� � �� � ��� � ,���.������ ��C��� � 7��� � ���
���� �����������!���� ������%�
B��&���!��������"������������A2%�����=66+� �����(��'���A�*������������������2,
������������7��������������%
2�
2 Angular Essentials
For a basic explanation of Promises, see section “2.9 Promises” on page 44.
async/await are the JavaScript keywords that greatly simplify asynchronous pro-
gramming:
In other words: With this concept, you only use a couple of keywords, but your
code will behave as though it is synchronous code. This is a fantastic change. You
get the benefits of async, with the readability of sync (or close to).
An example:
Look at our Promise function from page 44:
function asyncWriteFanMailToJuliaRoberts() {
var promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Mail sent!");
if (error) {
reject();
} else {
resolve();
}
}, 1000);
});
return promise;
}
What if we have more than one Promise before we continue? We can solve it in
two ways - one after the other or at the same time.
51
Ionic 4+
So the execution time is the sum of the execution times of all promises.. This can
lead to big performance problems. So if the Promises are not dependent on each
other, they should be executed at the same time.
Here are three Promises running at the same time and console.log('Spammed
all fan mails!') is waiting for all. The total execution time is the longest execu-
tion time of the promises.
52
2 Angular Essentials
Optimists who think that all their favorite actresses want to meet with them can
now wait for all answers and finally decide with which woman they want to meet
or arrange to meet them all ;-)
Above you see a function labeled async with a whole series of await commands
in it. This initialize() function is part of a service and gets all data from a data-
base by some sub functions. The sub functions are called one after the other. A
loading component is displayed during the data retrieval and only dismissed after
all data has been loaded.
I hope, you (better) understand this flow logic now.
53
Ionic 4+
Summary
In this chapter you met the most important concepts and structures of Angular,
which can be useful for you in the realization of your Ionic Apps:
54
3 The first app
Then write
$ ionic start first-app tabs
When we execute the command (with Enter), Ionic starts the following procedure:
Preparing directory ./first-app - done!
✔ Downloading and extracting tabs starter – done!
✨ IONIC DEVAPP ✨
55
Ionic 4+
Speed up development with the Ionic DevApp, our fast, on-device test-
ing mobile app
────────────────────────────────────────────────────────────
> npm i
added 1182 packages from 1208 contributors and audited 51887 packages
in 23.591s
56
3 The first app
�� IONIC APPFLOW ��
────────────────────────────────────────────────────────────
? Install the free Ionic Appflow SDK and connect your app? (Y/n)
Perhaps you get a few warnings, e.g. because of deprecated modules. Don't worry.
We can ignore them at the moment.
Answer the last question with n (no). We dont' need the Ionic Appflow SDK now.
After doing this, you may fix the identity used for this commit with:
57
Ionic 4+
58
1��6���7��������
6���������������������7��&��7�������������� ������������7�������%����������&��������"
�������������������� ����7�7� ��"�$�����$��$� ��������3��$�����������%�
2�
Ionic 4+
Local: http://localhost:8100
External: http://192.168.178.64:8100,
http://192.168.178.21:8100
60
1��6���7��������
C��D��! ����������#��������6����������6�������������"�KU����2��C����
�����D
C��D��! ��������#������6��������6�����������"�&-��2�C�������D�C����
�����D
C��D��! ��������%����#�����%�����6�������%�����6�����������%����"�-&T
�2�C�������D�C��������D
C��D��! ����� �����#�� ������6���� ������6�������� �����"�U�R��2�C���
���D�C��������D
C��D��! ����������#��������6����������6�������������"�TR����2�C����
����D�C��������D
C��D��! �������K����K���� ��#����K����K���� ���6������K����K�����
���6����������K����K���� ��"�S�&X��2��C��������D
C��D��! �������-����-���� ��#����-����-���� ���6������-����-�����
���6����������-����-���� ��"�X��-��2��C��������D
C��D��! �������&����&���� ��#����&����&���� ���6������&����&�����
���6����������&����&���� ��"�X��-��2��C��������D
C��D��! ����������������� ��#�������������� ���6�����������������
���6�������������������� ��"�T�����2��C��������D
C��D��! ����������#��������6����������6�������������"�X�&��A2�C����
����D�C��������D
C@4J5D���������KT&�������������! ���
C��D���� �����.��������� �����% ����
F�
��������
F�
1��6���7��������
6��������������� ������&��$������������������������$������������������������ �%
F1
Ionic 4+
<ion-content>
<ion-card class="welcome-card">
<ion-img src="/assets/shapes.svg"></ion-img>
<ion-card-header>
<ion-card-subtitle>Get Started</ion-card-subtitle>
<ion-card-title>
Welcome to my 1st Ionic app
</ion-card-title>
</ion-card-header>
<ion-card-content>
<p>This is my first Ionic app, yeah!</p>
</ion-card-content>
</ion-card>
<ion-list lines="none">
<ion-list-header>
<ion-label>Resources</ion-label>
</ion-list-header>
<ion-item href="...">
<ion-icon slot="start" color="medium"
name="book"></ion-icon>
<ion-label>Ionic Documentation</ion-label>
</ion-item>
<ion-item href="...">
<ion-icon slot="start" color="medium"
name="build"></ion-icon>
<ion-label>Scaffold Out Your App</ion-label>
</ion-item>
<ion-item href="...">
<ion-icon slot="start" color="medium"
64
1��6���7��������
����������������������(F����F;?���������;
��������?���������;.!�����V� ��1���B��� �?����������;
������?���������;
������?���������!��%(F���F;
��������?�������������(F�����F������(F���� �F�
����������������������(F������%���F;?���������;
��������?���������;/!����A��1��?����������;
������?���������;
����?���������;
?������������;
F2
��������
�5�� ������������������������9����
9��L����'���� ��3�����������&��&����7��&�����C���%�B��$�������������7������'��'��$%�
FF
3 The first app
src
In the folder src (source) we will spend most of our development time, as it con-
tains most of the code files that we will be editing. Here we will (soon) also create a
whole series of own code files.
app
This is the startup folder of an app with the bootstrap file main.ts. Here or in ap-
p.module.ts and app.component.ts you can place initialization code.
• tab1.module.ts is the module file of the page with all imports of further re-
quired modules.
• tab1.page.html contains the HTML code with the visible elements of a page.
• tab1.page.scss is a Sass file. In short, Sass is syntactically extended CSS and
takes care of style statements for a page.
• tab1.page.specs is used for test purposes.
• tab1.page.ts is the code behind the UI and our main playground for pro-
gramming.
app-routing.module.ts, app.component.html,
app.component.specs.ts, app.component.ts, app.module.ts
These are the top level files of our app. Their meaning basically corresponds to the
individual files on the page level (see tab1 above).
assets
contains all media files that are delivered with an app.
67
Ionic 4+
environments
contains predefined or custom information for the build process.
theme
contains central theming and styling files. After initial creation of an app, this folder
contains the file variables.scss. We will get to know these in more detail in
chapter 8 “Theming, Styling, Customizing” (starting on page 323).
global.scss
imports all global Ionic style files.
index.html
is the start file of an app. Typically, metadata and references to external JavaScripts
are put in the header of index.html. In the body tag you can find the app-root
tag, the entry point for every Ionic app.
package.json
contains a lot of meta-data about a project. Mostly it will be used for managing de-
pendencies of a project.
Others
All other folders and files that I have not listed here for the sake of clarity, we will
get to know in the further course of this book.
68
1��6���7��������
�5�� ���������$�������������������2����9���
)�$���L������������'��������&��������������'���&��%�B����������&�������������S����
�����7����&������������3����C���%�6������$�����$� ���'�����������������&"��������
��$����������'�����%�
#�����3������&�����������C����������7� ���%�6����$����
9������������������� ����������
�7����������7����������������������������"�$���������������������C����7� ����$���
9���������� ��
�����������&����$���������������$����$���
9������������
��������L������7����� ��3�����&����$���������&����-
F�
Ionic 4+
Summary
In this chapter you have programmed your first apps. Congratulations!
You now know ionic start and ionic serve and how to set up the Chrome
DevTools to simulate an app-like look.
You also have an overview of the project structure of an Ionic app.
70
���)�'��������
� ����������
�5�� 3����������
�7���&L���� �������������������������������������3����&�������������'����������� �%
Q�&����& ��L��������������������7������%�(����3��������� ������3�������&��� ��J�<��
�&������/�/6�������L'�����$������7� �$������'�����������7��*����$����������� "��&�
$������� ��T������,-
.�
��������
.�
4 Navigation
This command uses the Angular CLI to generate features such as pages,
components, directives, services, etc.
You can specify a path to nest your feature within any number of
subdirectories. For example, specify a name of
"pages/New Page" to generate page files at src/app/pages/new-
page/.
Usage:
$ ionic generate <type> <name>
Inputs:
Examples:
$ ionic generate
$ ionic generate page
$ ionic generate page contact
$ ionic generate component contact/form
$ ionic generate component login-form --change-detection=OnPush
$ ionic generate directive ripple --skip-import
$ ionic generate service api/user
73
Ionic 4+
All right, generate page sounds very good! Let's try this:
$ ionic g page pages/Favorites
In a new folder named pages we get a subfolder Favorites with all required page
files in it. We also get an updated app-routing.module.ts. In app-routing.mod-
ule.ts, as described in "2.5 Routing and Lazy Loading" (starting on page 36),
navigation between the pages of an app is organized. We will soon tune this mod-
ule.
Clean-up
The following cleanups have to be done:
74
4 Navigation
Attention: Don't delete the wrong list path – we have two of them! Make sure
you get the right lines.
75
Ionic 4+
},
{
path: 'regions',
loadChildren: './pages/regions/
regions.module#RegionsPageModule'
},
{
path: 'tour-types',
loadChildren: './pages/tour-types/
tour-types.module#TourTypesPageModule'
},
{
path: 'list',
loadChildren: './pages/list/
list.module#ListPageModule'
},
{
path: 'details',
loadChildren: './pages/details/
details.module#DetailsPageModule'
},
{
path: 'request',
loadChildren: './pages/request/
request.module#RequestPageModule'
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
76
4 Navigation
77
��������
���������$���
)�$�$������� �����������$�����&� ������&���$����������&%�6���
9������������
!&��$����S�$������&�����'���� /����������������������������<���������/�������
���$��&������������� ����� �"���&�������������&�����7��������'����������������&���
�������%�
./
���)�'��������
)�$��&������$��3������8�������������&������$���������'�����������������
�����'��������������&����� ��3�������������$����������@����$���A������*���&��&�0
���,�����'��������%
.�
Ionic 4+
4.3 Routing
app-routing.module.ts
The concepts of Routing and Lazy Loading in Angular/Ionic are described in chap-
ter 2 „Angular Essentials“ (see 2.5 Routing and Lazy Loading, starting on page 36).
As we have seen the root configuration for our router lives in the src/app/ap-
p-routing.module.ts file. For all our generated pages the CLI defined the
corresponding routes automatically. For example look at the route for the page
Details:
{
path: 'details',
loadChildren: './pages/details/details.module#DetailsPageModule'
}
It's a lazy loaded route that renders the DetailsPageModule where the outlet is
defined in the HTML in the app.component.html:
<ion-router-outlet main></ion-router-outlet>
When you navigate to the /favorites path in the browser, it will render the spe-
cific component in the HTML outlet.
A button or link is the most basic way to navigate to one of our defined routes.
Let's say, we want to navigate from Favorites to Details. We can simply create a
button in the favorites.page.html file like this one:
<ion-content padding>
<ion-button href="/details">Show details</ion-button>
</ion-content>
routerLink / routerDirection
A more advanced and my preferred way to switch to another page is using the
routerLink attribute in combination with the routerDirection attribute:
<ion-content padding>
<ion-button routerLink="/details"
routerDirection="forward">
80
4 Navigation
Show details
</ion-button>
</ion-content>
In this way we get a smooth forward animation while switching between pages.
The Ionic back button navigates back in the app's history upon click. <ion-back-
-button> is smart enough to know what to render based on the mode and when
to show based on the navigation stack. When there's no history, the attribute de-
faultHref can be used to define the url to navigate back to by default.
Let's complete our navigation stack by implementing a next route from Details to
Request.
81
��������
����?������ �����;
����?���������;=�) ���?����������;
��?������������;
?�����!�����;
5&��������'�����������7��-
9��L�����������������������&��������������������������7���) ���������!���-
?�������������������;
��?����� ������� ���B���(F�%��������F�
���������������� ���<��������(F����F;
����2�������J��������
��?������ ����;
?������������;
(��7��"��������J�!&��$���L���������$����&����������>�������$�$� ������������&���
7�����������������������>�6�����;&��������$� �������$��������������8����'�����
�7�������������%
/�
4 Navigation
@Component({
selector: 'app-favorites',
templateUrl: './favorites.page.html',
styleUrls: ['./favorites.page.scss'],
})
export class FavoritesPage implements OnInit {
tours = [
{ ID: 1, Title: 'City walk' },
{ ID: 2, Title: 'On the trails of Beethoven' },
{ ID: 3, Title: 'Villa Hammerschmidt' }
];
constructor() { }
ngOnInit() {
}
83
Ionic 4+
The Title property of every tour is then be displayed as text by Content Projec-
tion (see “2.6 Content Projection”, on page 39).
more exactly!
84
4 Navigation
@Component({
selector: 'app-details',
templateUrl: './details.page.html',
styleUrls: ['./details.page.scss'],
})
export class DetailsPage implements OnInit {
tour = null;
ngOnInit() {
console.log(this.activatedRoute);
this.tour = this.activatedRoute.snapshot.params;
}
To get data from the calling (previous) page, we can use the ActivatedRoute from
@angular/router. To use it we have to import it with
import { ActivatedRoute } from '@angular/router';
ActivatedRoute has a property snapshot, which in turn provides the tour object
through its params property. This is exactly the tour object, that of the previous
page over
[routerLink]="['/details', tour]"
85
��������
6�������������7�D�&���������9�E��9�������������& ��:���������������������������0
������@���& ���4������� �A�*�����%2�D�&���������9�E��9������"������������������1F,%
�5� ��1������������������������.������������������
)�$�$������������&�����������+��C�������*��������������A���& ���4������� �K"��%F�
��������+��C������"���������1�,�������$�����/���������������7������������&����
������������7���������������!���-
?����!�����;
��?�����������;
����?����� ����������(F�����F;
������?���������� ����;?����������� ����;
����?������ �����;
����?���������;����� ��/�����##?����������;
��?������������;
?�����!�����;
?�������������������;
�����
?������������;
=���L���&���������������-
/F
4 Navigation
Usually, the best way to tackle this situation is to simply pass an id through the
URL, and then use that id to grab the rest of the data through a provider/service.
We will explore this in the next chapter (chapter 5 “Services & Storage”, page 91).
But yet, as a first demonstration of using routerLink, we are satisfied with this sim-
ple solution.
https://ionicframework.com/docs/api/router-outlet
https://ionicframework.com/docs/api/back-button
87
��������
//
4 Navigation
Summary
In this chapter you've used Ionic's code generator to create some pages.
You got to know the app-routing.module.ts file, which defines the routes to the
pages of an app.
You now know how to use ActivatedRoute to transfer data from one app page to
the next.
You've got a pro tip to use the Augury Chrome Plugin to visualize the router tree
of an app.
89
��������� ���������� ���������������
��������
� ��������������������
�� ��������� ��������������������
������ ������ ����
������������������ ����������������������������
�������