Pgdmad 202 SLM
Pgdmad 202 SLM
Cross Platform
Mobile Application
Development
Course Writer
Subject Reviewer
Editors
ISBN-978-81-940577-6-5
All rights reserved. No part of this work may be reproduced in any form by mimeograph or
any other means, without written permission from the Dr. Babasaheb Ambedkar Open
University.
Printed and published by: Dr. Babasaheb Ambedkar Open University, Ahmedabad
ii
iii
Dr. Babasaheb PGDMAD-202
Ambedkar Open
University
iv
Block-1
Scenario of Mobile Application
Development
1
Unit 1: Cross Platform Mobile
Application Development 1
Unit Structure
1.1 Learning Objectives
1.2 Introduction
1.6 Basic Requirement For The Cross Platform Mobile Application Development
1.11 Assignments
2
1.1 LEARNING OBJECTIVES
1.2 INTRODUCTION
As per the survey by the leading statistics portal (sttista.com), in 2019 the
number of smart phone users is forecasted to reach 4.68 billion and will cross cross
5 billion at the end of the year 2019. This number represents 66 percentage of world
population. It shows the use of smart phone is growing rapidly. The applications play
3
supports developers to build applications for multiple mobile platforms at the same
time. In this book we will learn hybrid mobile application development using IONIC.
This unit discuss about the basic of mobile platform environment. We will also learn
the native mobile application development and cross platform (hybrid) mobile
application environment.
4
KitKat, Lollipop, Marshmallow, Nougat, Android Oreo were published. The
1.3.2 iOS
iPad, iPod Touch and Appel TV. The iOS is derived from the OS X. The OS
X is the operating system used in Apple computers.
The iOS, earlier known as iPhone OS, is a mobile operating system for
Apple mobile. The first version of the iOS was released in 2007 with the name
nt
stable release, iOS 12.2 was released on March 2019.
5
is a free download for the only Mac operating system users. It is not available
for the Microsoft Window operating system users. The SDK contains sets that
give developers access to various functions and services of iOS devices,
such as hardware and software attributes. The iOS SDK clubbed with Xcode
IDE.
user interface framework for building applications that run on iOS. The latest
tive to
the Objective-C language that employs modern programming-language
theory concepts with simpler syntax.
6
application platform that allows one application to run on multiple Window 10
devices such as personal computes and mobile
specific programming
mobile application development is specific for a mobile operating system or device.
That means before actual development of mobile application, developer needs to
finalize that on which mobile operating system or device it will be executed. Native
application is built for the use on a particular mobile operating system, it has the
ability to use device specific hardware or software. Native apps work with the
device's OS in the way that enables them to perform faster and more flexibly than
alternative application types. Native applications can be either installed on the
specific mobile by default or downloaded from Mobile OS specific app store. Figure-
1 shows the native mobile application development approach.
7
A native app is specially made and coded for a specific mobile platform in its
native programming language. The Swift and Objective C language are used to
develop mobile applications that are supported by the iOS (Apple) phone. The Java
or Kotlin language is used to develop mobile applications that run on the android OS
based mobile. The C# language is for Window 10 Phone. These all are the example
of native mobile application development.
The native mobile application development bring the trend of BYOD (Bring
Your Own Device). The BYOD refers to the policy of permitting employees to bring
their own mobile device to their workplace. The company needs to provide access
privilege to access company information and application on their mobile. We can find
many companies that provide mobile application to their employ through which they
can share company information. This kind of mobile applications mostly runs on
specific mobile operating system. Here it is compulsory that company employees
have mobile devices that have same mobile operating system.
satisfaction and job satisfaction. The main disadvantage of adopting the BYOD in
the company is that they need to develop same application for the multiple mobile
operating system. The illegal way of information discloser is second disadvantage to
adopting BYOD strategy.
Advantages
The developers code the application for the specific mobile OS. So it runs
smoothly over it.
Native applications achieve higher marks in speeds and performance.
In native apps, the look n feel and experience are much than other types
of mobile app.
Native apps offer fast access to inbuilt device utilities like the camera,
GPS, calendar, microphone, and other functions of the smartphone.
8
Disadvantages
Native apps need more time to develop. Creating and implementing the
design for every device takes more development time.
Developers usually have specialization in a single platform. To develop a
native app, we need as many development teams as the platforms on
which we want the app to be created. Multiple development teams imply
multiple budgets.
re multiple platforms
stand for the any mobile operating system or devices. A cross platform mobile
application also called Hybrid mobile application. Hybrid mobile application
development is required some specialized code.
A native mobile application which runs the web applications by using a Web
View is called Web View- Based Hybrid Mobile Applications. Generally Web View
based hybrid applications are developed using HTML5, Java Script and CSS3. It has
numbers of Java Script based gesture detection library to handle touch interaction
on screen. It look and feel like a native application but is actually run by website, It is
basically a web-based program to be put in a native app shell and connected to the
device hardware. The IONIC, Cordova, Angular are some of the example of Web
9
View based hybrid application development. Figure-2 shows the Web-View based
hybrid mobile applications development approach.
10
performance and user experience can be achieved almost the same as native
mobile application. The Xamarin with C#, Corona with C and Kony with Java Script
are the example of Cross Compiled Hybrid Mobile Applications.
11
in this approach, mobile application developed in single specific language and at
compile time (or run time) it converts it in to mobile specific native code.
Advantages
Hybrid mobile applications are developed once for all platforms. So we do
not require to hire different programmer. Due to that the development cost
is very low.
As we know hybrid apps are web apps incorporated in a native shell, so its
content can be updated as many times as you need or want. So, hybrid
apps have a low maintenance.
Hybrid mobile applications need to develop once, so we require short time
to develop and place it quickly on app store.
Disadvantages
Hybrid apps add an extra layer between the source code and the target
mobile platform, layer is call
performance.
The extra layer from hybrid development framework also makes
debugging a bigger task.
As compared to native app development, it is difficult to maintain a proper
user experience between the Android and iOS app. If you focus more on
iOS, the user experience will worsen for Android users and vice a versa.
Today, many tools and frameworks are available to develop cross platform
mobile applications. Below Table-1 shows the list of most popular tools used for
the cross platform mobile application development.
12
Framework
Ionic Web View Drifty Co.
React JS Web View Facebook
jQuery Mobile Web View jQuery Project
Cordova Mobile development Framework Apache
PhoneGap Mobile development Framework Nitobi
Xamarin Cross Compiled Xamarin
Robo VM Cross Compiled Robo VM AB
At the end of 2019, number of smart phone user will be cross 5 billion.
More than five million mobile applications available on leading app store.
A mobile app that is coded for specific mobile OS called native app.
Native application development require more time and cost.
A mobile app which can be developed for multiple platform by using single
codebase is call cross platform mobile application. It also call hybrid
application.
Hybrid app can be two type: Web view based or Cross compile base
A mobile app which run the web applications by using web view is called web
view based hybrid app.
Web view based app develop using HTML5, CSS and Java Script.
13
A mobile app which developed using specific language, will convert into
14
9. A mobile app build using CSS, HTM5 and JavaScript is call ______
A. Native mobile app B. Cross compile mobile app
C. Android app D. Web view based mobile app
10. Cross compile mobile convert into native app at ______ or _____ time
A. load, execute B. run, compile
C. execute , compile D. run, load
1. A 2. D 3. C
4. B 5. B 6. A
7. C 8. A 9. D
10. B
1.11 ASSIGNMENTS
15
Unit 2: Basic Of Development
Environment - Angular 2
Unit Structure
2.1 Learning Objectives
2.2 Introduction
2.11 Assignments
16
2.1 LEARNING OBJECTIVES
After studying this chapter, students should be able to understand:
Angular framework.
SPA (Single Page Application)
Angular for mobile applications development.
Angular architecture
Advantages and disadvantages of Angular
Necessary component to setup Angular environment.
History of Angular
Features of Angular4
Perquisite of Angular4
2.2 INTRODUCTION
In the previous unit we learnt about the cross platform mobile application
development environment. Various tools and frame works are available for the
same. Here in this book we will learn the cross platform mobile applications
development using Angular and Ionic framework. We also know that Ionic work is
based on Angular framework. So before learning Ionic framework we need to get
basic knowledge about Angular framework. This unit gives you insight of Angular.
We start with Angular framework and architecture follow by history of it. We also
discuss Angular environment and features of Angular4. This unit is explaining the
17
Angular provides inbuilt support for the animation, http services and many
more things. Angular empower developer who develops applications which live on
the web, mobile or the desktop. Angular is written in typescript.
In late 2013, web developer wanted to have their own custom JavaScript
libraries for reducing the number of code lines and implement complex functionalities
easily. A jQuery is the small and feature rich Java Script library that make things
easy for the web developer. But the main problem with jQuery is not real structure
which makes lot of confusion in larger projects. Here Angular comes into picture
and help a developer by providing structured environment. Angular is Java Script
framework that was specifically designed to help developer to build SPAs (Single
Page Applications) for web. A single-page application (SPA) is a web application or
website that interacts with the user by dynamic rewriting the current page rather than
loading entire new pages from a server. Figure-4 shows the different bewteen
traditional web page life cycle and SPA life cycle.
18
2.3.2 FEATURES OF ANGULAR
Before going into the detailed study of Angular, we need to learn the feature
of the Angular:
Modules
Modules are logical boundaries of the application. Instead of writing everything
into one application, we can build separate modules for each functionality of the
application. Angular apps are modular and to maintain modularity, we have
Angular modules or we can say NgModules. Every Angular app contains at
least one Angular module called root module. Module is made of three parts
called Bootstrap Array, Export Array and Import Array. The details of its
functionality can be seen learn in the next block of this book.
19
Figure-5 Architecture of Angular
Components
Each application consists of Components. Each component is a logical
boundary of functionality for the application. Each application is made up of
modules. Each Angular application needs to have one Angular Root Module.
Each Angular Root module can then have multiple components to separate
the functionality. Each component consists of Class, Template and Metadata.
It is represented by the Figure-6.
20
Templates
As the name suggests, templates are elements of Angular applications that
combine HTML with Angular markup, which are able to modify HTML
elements before displaying them on the screen. A template looks like regular
HTML, except for a few differences. Templates make use of pipes for
improving the user experience. Templates have two parameters like HTML
code and Class Properties.
Metadata
The information related to class is provided by metadata. This has an extra
data defined for the Angular class. It is defined with a decorator.A class
decorator is used for attaching metadata to a class. For providing the
necessary information required by Angular to create the component, class
Decorator makes use of configuration objects. Some of the configuration
options are directives, selector, and template URL.
Data Binding
If we are not using a framework, we have to push data values into the HTML
controls and turn user responses into some actions and value updates.
Angular supports data binding, a mechanism for coordinating parts of a
template with parts of a component. We should add binding markup to the
template HTML to tell Angular how to connect both sides. Binding markup is
responsible for connecting application data with the DOM. There are two
types of data binding, namely:
Directives
Angular templates are dynamic. When Angular renders them, it transforms
the DOM according to the instructions given by directives. A directive is a
21
custom HTML element that is used to extend the power of HTML. Two kinds
of directives exist, structural and attribute directives.
Structural directives alter layout by adding, removing, and
replacing elements in DOM.
Attribute directives alter the appearance or behavior of an
existing element.
Services
Service is a broad category around any value, function, or feature which
application needs. A service is typically a class with a well-defined purpose.
Anything can be a service. It is a part of component. Examples include:
logging service, data service, and business logic and application
configuration.
Dependency Injection
Dependency injection is the ability to add the functionality of components at
runtime.Most dependencies are services. Angular uses dependency injection
to provide new components with the services to the existing components.
Advantages
Consistency
Code consistency is an important goal to strive for any code base
system. Angular is framework is based on components and
services. In components based structure always look same, we can
add additional thing in to component but overall structure is always
look same. All the components services start on the same way. By
Productivity
With greater consistency, we get the benefit of productivity. When
we learn how to write one component we can write another
component by same general guidelines and code structure. Once
22
one. So development of application possible on fast track and
sufficient productivity.
Maintainability
Angular code can be built using TypeScript (it is improved
JavaScript) which provide lots of benefits along with easy
maintenance of the app.
Modularity
Angular is all about organizing code into modules. Everything you
or directives has to
be organized into one or more modules.
Disadvantages
To start with Anjular framework, we need to install several tools that Anjular
required. The detail installations of each components will be learned in block two
of the book.To setup the Angular environment we need the following component:
Node js
Node.js is a cross-platform runtime library and environment for running
JavaScript applications outside the browser. This is a free and open
source tool used for creating server-side JS applications. Node.js is useful
23
to build fast and scalable server-side networking applications. This
framework is best suited for building single-page client-side web
applications.
24
be powerful framework for the web development. Thus Angular.js development
began to accelerate.
There are three major releases of Angular. The first version was released is
AngularJS, which is also called Angular1. Angular1 is followed by Angular2, which
came with a lot of changes compared to Angular1. AngularJS is totally different from
Angular2. Some of the differences between AngularJS and Angular2 are mentioned
below:
2018. However for the cross platform mobile applications development using Ionic,
we will learn Angular4.
25
2.5 FEATURES OF ANGULAR4
-
Angular4 is smaller and faster. It reduces bundle file size upto 60% which
improves the application speed.
Angular4 is compatible with newer version of TypesScript2.2
Majority of Angular Universal code has been merged into Angular core.
Animations taken from the Angular core and set within their own package
ions, the excess code
Next block of this book will discuss Angular basics. The block will teach you,
how to write Angular code. Before moving to the next block, you should have a
basic understanding of HTML, CSS, Java Script and Document Object Model
(DOM).
26
The eight components are Modules, components, Templates, Metadata, Data
Binding, Directives, Services and Dependency Injection.
Modules are logical boundaries of the application.
Each application consists of Components. Each component is a logical
boundary of functionalities.
Templates are elements of Angular applications that combine HTML with
Angular markup, which are able to modify HTML elements.
Metadata is a information related to class used by Angular.
Data binding is a mechanism for coordinating parts of a template with parts of
a component.
Angular templates are dynamic. A service is typically a class with a well-
defined purpose. And Dependency injection is the ability to add the
functionality of components at runtime.
To develop application using Angular, we should have a knowledge of
HTML5, CSS, JavaScript and DOM architecture.
27
2.9 CHECK YOUR PROGRESS: POSSIBLE ANSWERS
2.11 ASSIGNMENTS
28
Unit 3: Basic Of Development
Environment - IONIC 3
Unit Structure
3.1 Learning Objectives
3.2 Introduction
3.11 Assignments
29
3.1 LEARNING OBJECTIVES
3.2 INTRODUCTION
In this unit we will discuss about the basic fundamental of Ionic. Ionic
framework provides a facility to the mobile developers to develop cross platform
mobile application. Ionic based mobile application need to code once and run on any
mobile operating system like Android, iOs and Window phone. Ionic is an HTML5
mobile app development framework targeted at building hybrid mobile apps. Hybrid
apps are essentially small websites running in a browser shell in an app that have
access to the native platform layer. Hybrid apps have many benefits over pure native
apps, specifically in terms of platform support, speed of development, and access to
3rd party code.
Ionic as the front-end UI framework handles all of the look and feel and UI
interactions that app needs in order to be compelled. Ionic provide a native style
mobile UI components and layouts that are the same as we get with native SDK on
iOS or Android. Here we will learn about the basic of the Ionic framework and
evolution of Ionic. After that we will talk about Ionic stack and prerequisites for Ionic
learning.
Ionic framework is the one of the popular frameworks for the cross platform
mobile application development. Using this framework, mobile app developer can
30
create native-looking mobile applications. Ionic framework is based on web
technologies such as HTML5, CSS and JavaScript. All these three technologies are
open source. Ionic developer can build and upload mobile app on market place
without any cost because Ionic is also open source. Developers and users should
not pay any charge to use it.
The developers of Ionic believe that HTML5 would rule on mobile over a time,
exactly as it has on desktop. Ionic is an HTML5 mobile app development framework
targeted at building hybrid mobile apps. Hybrid apps are essentially small websites
running in a browser shell in an app that have been accessed to the native platform
layer. Hybrid apps have many benefits over pure native apps, especially in terms of
platform support, speed of development, and access to 3rd party code.
Those who are familiar to web development, will find the structure of an Ionic
That means we can use any kind of HTML, CSS, and JavaScript we want. The only
difference is, instead of creating a website that others will link to, we are building a
self-contained application experience. The bulk of an Ionic app will be written in
HTML, JavaScript, and CSS.
Ionic framework is built with Angular, a widely used and well tested
framework. The combination of th
SPA (Single Page Application) based mobile application that is easier to organize.
Each mobile operating system has their requirement for UI components. Ionic
provides a readymade UI mobile component and feature of automatic
implementation based on the mobile operating system it built for. So mobile
application users fill the UI same at the native application provide. Ionic use SASS
(Syntactically awesome style sheets) to generate CSS that visualize the Ionic
application. SASS is a preprocessor scripting language that is interpreted or
compiled into Cascading Style Sheets (CSS). SASS provides several advantages
over writing CSS directly. Detail will be shown later in this book.
Ionic also provides the JavaScript features for app developers for developing
Ionic applications. All the JavaScript features are built on Angular. App developers
use the JavaScript feature through the Angular.
31
3.3.1 FEATURE OF IONIC
Ionic help to build cross platform mobile applications using HTM5 with the use
of Angular framework. Ionic provides a great range of tools and service using the
framework. Let us see key features of Ionic framework.
Ionic uses Angular MVC architecture for building SPA (Single Page App)
specifically for mobile devices.
SASS provides plenty of UI components for creating robust and rich apps.
It provides JavaScript components. These components are extending
CSS components with JavaScript functionalities that are specifically made
for the mobile elements, which is not possible only with HTML and CSS.
Development of the app is very vital only once as well as it would be
compatible with all the mobile devices. Also, it needs very limited use of
time, resources and efforts, and helps in giving an integrated look and
feel. It provides easy and feasible cross platform mobile application
environment
Ionic has CLI. It is nodeJS utility which is the command for starting,
building, running and emulating Ionic applications.
Ionic View is very useful platform for uploading, sharing testing mobile
application on native devices.
Ionic is released under MIT license. Ionic is free and open-source.
Advantages
Ionic framework provide cross platform mobile application environment. It
means we can build mobile application that run on iOS, Android, Window
Phone or other mobile operating system.
To start mobile application is easy with the help of pre-generated app
setup with simple layout.
32
The mobile application is built in modular way, so it is easy to be
maintained and updated.
Ionic framework is built with Angular framework, which is a product of
Google. So updates comes regularly that help fast and speedy mobile
development.
Disadvantages
Testing of it is little tricky as browser does not always give right
information about mobile environment.
Today lots of mobile devices and operating system are available in
market. Usually all need to cover them for Ionic framework support.
It will be hard to combine different native functionalities.
Sometimes compatibility issues arises, which leads to build errors that are
hard to debug.
Cross platform applications are slower than native applications.
To start with Ionic framework, we need to install several tools that Ionic
requires. It is little challenging task to install it. The detail installations of each
component will be shown in block three of the book. We need to setup two kinds
of components: The base of Ionic installation and platform specific SDK
installation. The base installation requires tools that need to build mobile
applications and preview in browser. The platform specific installation requires to
setup native development environment. As we know our mobile application will
be built based on web technologies, the platform specific installation gives
access of emulators to test the applications on mobile device.
NodeJS
33
written in JavaScript that can be run anywhere. Both Cordova CLI and
Ionic CLI are written using Node.
Git
Ionic CLI holds Git for the management of templates. Git is a free and
open source distributed version control system designed to handle
everything from small to very large projects with speed and efficiency.
Ionic CLI
Ionic compatibility starts at iOS 6 and Android 4.1, older versions than
that will not be officially supported. The Ionic Framework also provides a
useful command line interface (CLI) that makes it easy to start, create,
compile and export mobile applications. The Ionic framework provides
some useful functions such as ionic.Platform.isIOS(),
ionic.Platform.isAndroid() and ionic.Platform.isWindowsPhone() which
can be used to detect on what OS the current application is running on.
34
Platform Specific SDK Installation:
By setting up above component we can start developing applications
and test it in browser. But if we want to test it on either device emulator or
actual device we need to set up platform specific SDK. Currently Ionic
officially supports iOS, Android and Window Universal platform.
iOS
If we want to build application for iOS, we need to install Xcode
for emulation and distribution of app. Xcode is available for Mac os.
Android
If we want to build application for Android, Android can be done
on Window, Mac or Linux system. We need to install Android SDK
tools. If we require IDE then we should install Android Studio.
Window Universal
Window universal supports only on window machine. We need
The Ionic 3 or simply "Ionic", are built on Angular (web framework). However,
The Ionic3 release allows you to choose your User interface framework from Angular
(web framework), React (JavaScript library) and Vue.js. The latest release Ionic 4
35
was come up in January, 2019. Every release come up with new components and
updates in framework.
Cordova
The Cordova is used as an interface between the web view and the
between two technologies, web technology and native web view. Cordova is
provide mobile platform support form iOs, Android, Window Phone,
Blackberry and FireOS. It is an open source framework developed in 2009.
Angular
As we have discussed a lot about Angular in last unit, there is no need
to discuss it here in detail about Angular. Basically Angular provide SPA
(Single Page App) development with MVW (Model View Whatever) to
build complex web applications. Ionic team decides to take advantage of this
feature of Angular and they build the application upon it.
Ionic Framework
Ionic framework is an open source provided under MIT license. The
primary feature of the Ionic Framework is to provide the user interface
components that are not available to web-based application development. For
example, a tab bar is a common UI component found in many mobile
applications. But this component does not exist as a native HTML element.
The Ionic Framework extends the HTML library to create one. These
components are built with a combination of HTML, CSS, and JavaScript, and
each behaves and looks like the native controls it is recreating. Ionic also
provides some additional tooling to help build mobile applications.
36
Ionic CLI
The Ionic CLI (Command Line Interface) is a command line tool that is
used to manage Ionic applications. It allows you to create an Ionic application
easily, and provides tooling for serving your application throughout
development, and building your application for production.
Capacitor
Capacitor is a separate project to Ionic (it is still created by the Ionic
team), but it is used in conjunction with Ionic. Capacitor provides a common
API for accessing native functionality across different platforms. This means
that if you want to access functionality like the camera, you can use the same
code for iOS and Android without worrying about the underlying native
implementation on each platform. Capacitor also allows you to build your
Ionic application as a native application for iOS/Android/Desktop.
Appflow
Ionic Appflow is an optional platform which is also provided by the Ionic
team that you can use in conjunction with your Ionic applications. This is a
paid solution that provides functionality like continuous deployment and
automatic application builds.
Ionic applications are built using HTML5, CSS and JavaScript. So you should
have basic knowledge of these technologies and how to implement these
technologies to build web applications. Here in this book Ionic application
development code used JavaScript based on Angular4, this means you should know
fundamental of Angular4. However we will learn the Angular4 in block2 in detail.
Ionic is all about cross platform mobile application development, so probably you
should have basic knowledge for the operating the iOS and Android devices.
37
In short Ionic is built on top of AngularJS and Apache Cordova, you will need
to have basic knowledge about web technologies. You should familiar with HTML,
CSS and JavaScript, if you want to understand all the information provided by the
book.
38
3.10 FURTHER READING
3.11 ASSIGNMENTS
Write answer of the following Questions
1. Explain Ionic framework.
2. List the features of Ionic.
3. List the advantages and disadvantages of Ionic.
4. Write a short note on Ionic environment.
5. Write a short note on Ionic Stack.
39
Block-2
Working with Angular
40
Unit 1: Introduction to Angular
1
Unit Structure
1.1 Learning Objectives
1.11 Assignments
41
1.1 LEARNING OBJECTIVES
After studying this chapter, students should be able to understand:
The history of SCRIPT and Why SCRIPT
The Different available SCRIPTING languages
Difference between AngularJS and Angular with syntax
General and Core features of Angular
Advantages and Disadvantages of Angular
You should place all your JavaScript code within <script> tags (<script> and
</script>) if you are keeping your JavaScript code within the HTML document itself.
This helps your browser distinguish your JavaScript code from the rest of the
code. As there are other client-side scripting languages (Example: VBScript), it is
highly recommended that you specify the scripting language you use. You have to
42
use the type attribute within the <script> tag and set its value to text/ JavaScript like
this:
<script type="text/javascript">
<html>
<head>
<title>My First JavaScript Example</title>
<script type="text/javascript">
</script>
</head>
<body>
</body>
</html>
There are many scripting languages some of them are discussed below:
43
Scripting languages, on other hand, solves different problems:
Building applications f
Controlling applications that have a programmable interface
Writing programs where speed of development is more important than run-
time efficiency.
Angular was created by Google and released in 2010 as AngularJS the 1.x
version . The initial release for the Angular 2.x version was on September 14, 2016.
The second major revision was initially referred to as AngularJS 2 or 2.0 but was
44
1.4 GENERAL FEATURE
Developers prefer this framework for their front-end development for a
development process much more efficient. These tools also seamlessly work
together in tandem providing you with an efficiently compiled program. Given below
are five features of Angular that make it the best for web development as framework.
One of the best and popular features of angular is the fact that it makes use
of a unit testing technique that helps developers to produce high quality apps. The
code is divided into the smallest testable parts i.e. units. This also helps you easily
detect any flaws or mistakes in each line of the code.
45
injected and tested to see if the request is returned with the expected data. This
improves you make sure that each and every component of your application works
exactly as required.
Data binding in Angular is a two way road. This means that the view layer of
the architecture is always an exact representation of the model. Unlike in other apps,
the model and view layers are continuously updated to remain in sync with one
another.
So any changes you make in your model layer will automatically be reflected
in your view layer and vice versa. This again saves a significant amount of time in
coding the connection between the two whenever a change is made.
46
Requires Writing Less Code
Angular needs a lot less coding than others. You do not have to write code to
manually, directives are separate from the app code and can be written parallelly
etc. All of these collectively decrease the amount of coding that is required,
significantly.
Developed by Google
Figure-11 Angular
47
Progressive Web Application
This feature of angular on application makes feel like native apps with mobile
web apps along with add-ons like offline experience and push notifications. This is
made possible as Angular can create code and configuration on its own with
Angular-CLI and it offers service workers through the @angular/service-worker.
$ ng set apps.0.serviceWorker=true
This tool is by default applied. The build optimizer tool makes the application
faster and lighter by removing additional parts and runtime code as well. This tool
decrease the size of script and enhance the speed of the application.
Angular team added the domino to the platform-server.it enhance the more
DOM manipulations are supported within server-side contexts. Team also added the
BrowserTransferModule and ServerTransferStateModule. Both modules enable you
to transfer information between the server and client-side versions of the application.
This is helpful for developers when their application accessing data over HTTP. This
means there is no need to make another HTTP request once the application
reached client-side.
HttpClient
Using the HTTP Client developers can replace the HttpModule with
HttpClientModule from @angular/common/http, inject the HttpClient service, and
remove the map(res => rex.json()) calls that is no longer required.
48
TypeScript is also upgraded to the latest version of TypeScript , which allows
connecting to the standard TypeScript compilati on pipeline
ng serve
This allows exporting, you can give multiple names to your directives and
components. Exporting a component/directive with multiple names can help users to
migrate smoothly without breaking changes.
Animation
Angular now came with some updates in Animations, where you can animate
by using :increment and :decrement based on numerical value changes. you can
also activate and deactivate the animations using values that are associated with
data binding. The .disabled attribute of the trigger value is constrained to do this.
49
Though Angular comes with a lot of merits, here are some points of concern as
demerits:
Not Secure
are not safe. Server side authentication and authorization is must to keep an
application secure.
Not degradable
visible except the basic page.
50
1.8 LET US SUM UP
All scripting languages are known as programming languages.
Scripting languages do not require the compilation step and interpreted.
JavaScript is a very powerful client-side scripting language. JavaScript is
used mainly for interaction of a user with the webpage.
There are many(Ruby,Python,bash,Nodejs,PHP) scripting languages
Angular was created by Google and released in 2010 as AngularJS the 1.x
version
Angular tools make it the best for web development as framework.
Angular release is mainly focused on making Angular framework smaller,
faster, and easier to use.
Build optimizer is by default tool.
New feature brought a lot of improvements in Angular Compiler to make re-
builds of the applications faster, mainly for AOT and production builds.
Some times angularbecome the not secure and not degradable.
Modularity is a much core functionality has moved to modules.
51
5. Angular follows the ________ architecture.
A. MVV C. MMC
B. MVC D. MV
55
1.11 ASSIGNMENTS
56
Unit 2: The Basic of Angular
2
Unit Structure
2.1 Learning Objectives
2.10 Assignments
57
2.1 LEARNING OBJECTIVES
To build web applications that can meet the needs of users is not a small
task. The quality and complexity of applications is ever increasing, and so are users
expectations for quality and capabilities. Angular exists to help developers deliver
applications to meet these demands.
58
Powerful ecosystem with a large community
Angular supports number of third-party libraries, UI libraries, blog posts, and
events. Angulars active community provides a great foundation on which to learn
and should instill confidence that it will remain a valuable technology.
59
Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript
version 1.8. This brings a lot of difference in the performance. To install Angular 4,
the Angular team came up with Angular CLI which eases the installation. You need
to run through a few commands to install Angular 4.
We first need to install nodejs and npm with latest version to get started installation
of Angular. The npm package gets installed along with nodejs.
https://nodejs.org/en/
Figure-12 Console
To check the version of npm, type command npm v in the consol. It will display the
version of npm as shown below.
60
Figure-13 Check Version
Now that we have nodejs and npm installed as step 1 shown, let us run the angular
cli commands to install Angular 4. You use the Angular CLI to create projects,
generate application and library code, and perform a variety of ongoing development
tasks such as testing, bundling, and deployment.Install the Angular CLI globally.
To install the CLI using npm, open a terminal/console window and enter the
following command:
Workspace contains the files structure for one or more projects. A project is the set
of files that comprise an app, a library tests.
Run the CLI command ng new and provide the name my-app, as shown here:
ng new first
61
It also creates the following workspace and starter project files:
Angular includes a server, so that you can easily build and serve your app locally.
cd first
ng serve open
The project first is created successfully. Internaly its install all the package which are
required to Angular 4. Now we have to change the view and behavior of app so for
the need a one smart editor.You can use the IDE like Visual Studio Code IDE, Atom,
Webstrom, Sublime Text, etc.
62
2.4 FIRST EXAMPLE IN ANGULAR
To create an application in Angular, Angular CLI is an awesome tool to start.
It creates fully functional well-structured project which we can take forward.
After performing this steps open your project in sublime or visual studio code
to use and understand the project structure.
The project structure of Angular 4 application which Angular CLI created for
us. We have already created HELLO-WORLD project, so we will use that project to
get idea about project structure.When we open the Angular 4 project in editor, we
can see three main folders e2e, node_modules, src and different configuration files.
63
Following table describe the basic use of this files and folders.
Node_modules Node.js creates this folder and puts all third party modules
listed in package.json .
64
editor.config It contains the setting of your editor. It has parameter like
style, size of character, line length.It works for UI.
.gitignore We can define all the folders and files which we want to
exclude from our repository in our git.
karma.conf.js It has configuration for writing unit tests. karma is the test
runner and it uses jasmine as framework. These both tester
and framework are developed by angular team for writing
unit tests.
package.json The Jason based file contains all the dependency modules
which are required for our application. if you want to use _js
library or any other library just add name and version of that
dependency library in package.json and execute command
npm install. It will execute all the dependencies and
download in node_modules folder.
README.md Is contains basic documentation for your project, pre-filled
with CLI command information. Just make sure to enhance
it with project documentation so that anyone checking out
the reputation can build your application.
protector.conf.js It contains testing configurations.
tsconfig.json The ts stands for typescripts. Typescripts are used for
developing angular applications since Angular 2 came out.
It contains the configurations for typescripts.
tslint.json Used for building application with consistent code style. We
can change the configuration that defines how our
application should be build.
Src/favicon.ico Its favicon icon for your website or an application.
Src/index.html It contains html code with head, and body section. It is
starting point of your application.
Src/main.ts It is starting point of typescript file in your angular
application. It contains library which are imported by your
angular project.
Src/polyfill.ts It is used for browser compatibility.
Src/style.css It has all the styles and css for your angular 4 project.
65
Src/test.ts This file is used to write unit tests.
Src/tsconfig.app.json It contains the configuration about how your application
should compile.
App/* This folder contains component and ts files.
app /app.module.ts It contains the entire library which are imported and used in
66
2.5 ANGULAR DIRECTIVES AND STRING INTERPOLATION
2.5.1 DIRECTIVES
Component Directives
These form the main class having details of how the component should be
processed, instantiated and used at runtime.
Structural Directives
A structure directive basically deals with manipulating the dom elements. Structural
directives have a * sign before the directive. For example, *ngIf and *ngFor.
Attribute Directives
Attribute directives deal with changing the look and behavior of the dom element.
You can create your own directives as shown below.
67
In one-way data binding, the value of the Model is inserted into an HTML
(DOM) element and there is no way to update the Model from the View. In two-
way binding automatic synchronization of data happens between the Model and
the View.
Sample Example:
Sample Example:
Display array items We can use interpolation along with ngFor directive to
display an array of items.
DomainObject.ts
68
//code
}
}
app.component.ts
@Component({
selector: 'app-root',
template: `
<h1>{{title}}</h1>
<h2>The name is : {{domainObjectItem.name}}</h2>
<p>Data Items:</p>
<ul>
<li *ngFor="let d of domainObjects">
{{ d.name }}
</li>
</ul>
`
})
export class AppComponent
{
title = 'App Title';
domainObjects = [
new DomainObject(1, 'A'),
new DomainObject(2, 'B'),
new DomainObject(3, 'C'),
new DomainObject(4, 'D')
];
domainObjectItem = this.domainObjects[0];
}
69
2.6 ANGULAR EVENT
Angular event is known as Angular event binding. Event binding is used to
build interactive web application with the flow of data. The flow of data various from
component to element and from element to component.
In some cases user will not only just view the information or data on web
application, but also would like to interact with these application using different user
action like clicks, keystrokes and change event.
To define event binding syntax will have a target event name within
parentheses on the left of an equal sign, and a quoted template statement on the
right.
Example: onclick()
@Component({
selector: 'app-ex',
template: `
<div>
</div>
70
})
onClick(){
The target event is identified by the name within the parenthesis, ex: (click), which
represents the click event. In the example, above we saw the target click event
bound to the 'onClick()' method, which will listen to the button's click event.
We can also use the prefix on-, in event binding this is known as canonical form.
If the name of the target event does not match with the element's event, then
Angular will throw an error "unknown directive".
71
Angular provides a common developer experience through its CLI tooling
which includes the generating, building, testing and deploying apps.
Angular supports number of third-party libraries, UI libraries, blog posts, and
events
Angular comes with a leaner core library and makes additional features
available as separate packages that can be used as needed.
Angular4 uses TypeScript 2.2 version whereas Angular 2 uses TypeScript
version 1.8
To setup the Angular 4 need to install nodejs and npm.
Angular works on command thatswhy need the CLI.
Angular project is known as workspace.
The description knowledge of files and folder of angular project is important.
All the files and folder have a meaning ful files
Angular supports the three types of directives.
String Interpolation also known as Angular Interpolation, uses template
expressions in double curly {{ }} braces to display data from the component,
String Interpolation also evaluated the string expression.
72
4. To serve the angular ______ command is used.
A. ng serve C. ng
B. serve D. ds Server
6. _______can be used to display and evaluate strings into the text between HTML
element tags and within attribute assignments.
A. String C. Binding
B. Interpolation D. Event
56
2.10 ASSIGNMENTS
1. What is Framework?
2. State the reason: Angular is a platform not a framework.
3. Write down the steps for angular setup.
4. Explain the file structure of angular application.
5. Explain the string interpolation with example.
6. Explain the event with sample code.
76
Unit 3: Introduction to MVC
3
Unit Structure
3.1 Learning Objectives
3.10 Assignments
77
3.1 LEARNING OBJECTIVES
Angular (Angular 2, 4,
the ground up, replacing the now well-known AngularJS framework (Angular 1.x).
More that just a framework, Angular should be considered as a whole platform which
comes with a complete set of tools like its own CLI, debug utilities or performance
tools.
Angular was designed for the use of design patterns you may not be
accustomed to, like reactive programming, unidirectional data flow and
centralized state management.
Reactive programming
The Angular is now a reactive system by design. Although you are not forced to use
reactive programming patterns, they make the core of the framework and it is
definitely recommended to learn them if you want to leverage the best of
Angular.Angular uses RxJS to implement the Observable pattern.An Observable is a
stream of asynchronous events that can be processed with array-like operators.
78
simpler and more predictable data flows in applications, along with substantial
performance improvements.
Generally AngularJS follows the MVC architecture, the diagram of the MVC
framework as shown below.
Models are used to represent your real data. The data in your model can be
as simple as just having primitive declarations. If you are maintaining a employee
application, your data model could just have a empid and empname.
Views are used to represent the presentation layer which is provided to the
end users.
79
The Controller represents the layer that has the business logic. User events
trigger the functions which are stored inside your controller. The user events are part
of the controller.
Angular Architecture
app.component.css
app.component.html
app.component.spec.ts
app.component.ts
app.module.ts
if we open the app.module.ts which shows some libraries which are imported like
80
The declaration becomes the parent component. This include the AppComponent
variable. This is in build component. If you would like to create a component form
command line then follows this syntax.
ng g component new-cmp
When you run the above command in the command line, you will receive the
following output
installing component
create src\app\new-cmp\new-cmp.component.css
create src\app\new-cmp\new-cmp.component.html
create src\app\new-cmp\new-cmp.component.spec.ts
create src\app\new-cmp\new-cmp.component.ts
update src\app\app.module.ts
new-
style.
new-
new-
new-cmp.component.ts used to define the module, properties, etc.
81
3.4 INTRODUCTION TO PIPES
Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and
4+.Sometimes application starts out with what seems like a simple task: get data,
transform them, and display them to users. Getting data could be as simple as
creating a local variable or as complex as streaming data over a WebSocket.
Once data arrives, you could push their raw toString values directly to the
view, but that rarely makes for a good user experience.
For example, in most use cases, users prefer to see a date in a simple format
like April 15,2019 rather than the raw string format Fri Apr 15 2019 00:00:00 GMT-
0700 (Pacific Daylight Time).
Example:
Using Pipes
Pipes takes any integers, strings, arrays, and date as input separated with | to be
converted in the format as required and display the same in the browser.
82
Will convert the title variable in uppercase and lowercase.
A pipe takes in data as input and transforms it to a desired output. In next example
pipes to transform a component's birthday property into a human-friendly date.
In component.ts file
Built-in Pipes
83
Example of Built in pipes
Componenet.ts file
Component.html file
Output
Welcome back Nirav Suthar
On Jun 26, 2016 at 7:18 you reserved room 205 for Nov 14, 2025 for a total cost of
$99.99.
Parameterizing a pipe
A pipe can accept any number of optional parameters to output. To add parameters
to a pipe, follow the pipe name with a colon ( : ) and then the parameter value (such
as currency:'EUR'). If the pipe accepts multiple parameters, separate the values with
colons (such as slice:1:5)
84
Component.html file
The parameter value can be any valid template expression, such as a string literal or
a component property. In other words, you can control the format through a binding
the same way you control the birthday value through a binding.
Chaining Pipe
Pipes may be chained. The combination of more then one pipe is called chaining
pipe. we can use chain pipes together in potentially useful combinations.
Component.html
<p>your birthday is
{{ birthday | date | uppercase}}</p>
<p>your birthday is
{{ birthday | date:'fullDate' | uppercase}}</p>
85
Below example shows how to create a custom pipe.
Here, we want to create the cube custom pipe. We have given the same name to
the file and it looks as follows
app.cube.ts
To create a custom pipe, we have to import Pipe and Pipe Transform from
Angular/core. In the @Pipe directive, we have to give the name to our pipe, which
will be used in our .html file. Since, we are creating the cube pipe, we will name it
cube.
As we proceed further, we have to create the class and the class name is cubePipe.
This class will implement the PipeTransform.
86
@NgModule({
declarations: [
cubePipe,
AppComponent,
NewCmpComponent,
ChangeTextDirective
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<h1>Custom Pipe</h1>
<b>Cube root of 64 is: {{64 | cube}}</b>
<br/>
87
listening to these events. The event binding system provides us the way to attach a
method defined in a component with an event. Event binding is built on top of the
events defined in the DOM objects.
With Angular, there are two ways to handle an event on an HTML element.
The following line of code shows both the ways for handling a click event on a
button:
The method save has to be defined in the component class. Any DOM event
can be either prefixed with on- or can be enclosed inside parentheses to bind it with
a method in the component class.
involve any abstractions which has to be written for any event on the page, this
model is extensible. Any new events added to a DOM element can be bound to
functions in the component using this syntax without writing any piece of new code.
Events can be used to run a piece of logic based on the action taken by the user. It
may include changing values of a few fields in the component, posting data to a
REST API, moving to a different page or anything else. As the events directly
an entry to the event loop.
triggered. So, any values modified by the event handler will be detected by the
change detection system and the changes are applied on the page.
@Component({
selector: 'app-demo',
template: `<div>{{submitText}}</div>
<button class="btn" (click)='save()'>Save</button>`
88
})
export class DemoComponent {
public submitText: string = 'Not submitted yet.';
save(){
this.saveText = 'Submitted successfully!';
}
}
The above component has a div element and a button. The div element has an
interpolation applied, text of the interpolated expression is modified in the click event
handler of the button. You will see that the text inside the expression is modified
after clicking the button.
If an event has to perform a single action like changing a simple value, it can be
done in the HTML instead of writing a separate method. The following snippet shows
an example:
But if the event involves a few more lines of logic, it should be kept outside HTML to
separate the concerns. This way, the code in the event handler can be unit tested as
well. The event handling method gets access to the event object, which is same as
the object passed into any DOM event handler. This object gives us access to the
information about the event. The following snippet shows how to pass the event
object from HTML to the event handling object:
The $event object is same as the object that the browser sends when an event is
triggered on an HTML element. We can get details of the event like source of the
event, target element, type of the event, co-ordinates on the page and screen where
the event triggered, as well as many other details.
89
The following snippet shows a component handling two events on a button:
@Component({
selector: 'app-demo',
template: `<div>{{saveText}}</div>
<button class="btn" (click)='save($event)'
(mousemove)="mouseMove($event)">Save</button>
<div>{{x}} {{y}}</div>`
})
export class DemoComponent {
public submitText: string = 'Not submitted yet.';
public x: number;
public y: number;
submit($event: Event){
this.saveText = 'Submitted successfully!';
console.log($event);
}
mouseMove($event: MouseEvent) {
this.x = $event.x;
this.y = $event.y;
}
}
The component in the above snippet has a button, on which the click and mouse
move events are handled using methods in the component. The click event changes
the text displayed in the div element and the mouse move event updates values of
the co-ordinates displayed on the screen.
The feature two-way binding in Angular is derived from the property and event
bindings. The property and event bindings are directed one way with the former
receiving data into view from the component object and the later sending data from
90
the view to the component. The two-way binding is a combination of these two
bindings; it gets the data from the component object to the view and sets the data
from view to the component object.
The field name is two-way bound on the input box. When it is rendered on a
page, it shows the existing value of the field and when the value is modified on the
screen, it updates the value in the field. The change in the value of the field is
immediately reflected in the interpolation in the div element next to the input
control.To use the ngModel directive, the FormsModule has to be added to the
applicatio
FormsModule:
91
})
export class AppModule { }
@Component({
selector: 'app-demo',
template: `
Name: <input type='text' [(ngModel)]='name' />
<div>Name is: {{name}}</div>
`
})
export class DemoComponent {
public name: string = "Virat";
}
The textbox is bound to the field name in the template. When you type something in
the textbox, you will see that the content in the div changes automatically.
the ground up, replacing the now well-known AngularJS framework (Angular
1.x)
Angular was designed for the use of design patterns
The Angular is now a reactive system by design
The AngularJS where one of its selling points was two-way data binding
which ended up causing a lot of major headaches for complex applications,
Angular now enforces unidirectional data flow.
The main goal of using a centralized state management is to make state
changes predictable by imposing certain restrictions on how and when
updates can happen, using unidirectional data flow.
Models are used to represent your real data. The data in your model can be
as simple as just having primitive declarations. If you are maintaining a
92
employee application, your data model could just have a empid and
empname.
Views are used to represent the presentation layer which is provided to the
end users.
The Controller represents the layer that has the business logic. User events
trigger the functions which are stored inside your controller. The user events
are part of the controller.
Architecture of an Angular Application is based on the idea of Components.
An Angular application starts with a Top level component called Root
Component
The @Component() decorator identifies the class immediately below it as a
component, and provides the template and related component-specific
metadata.
Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and
4+.Sometimes application starts out with what seems like a simple task: get
data, transform them, and display them to users.
Pipes may be a user pipes, buil-in pipes and custom pipes.
Event binding refers to the data binding. Data binding is very important
feature of Angular. Data binding is used for front-end framework, Interpolation
and property binding in Angular.
The event binding system provides us the way to attach a method defined in
a component with an event. Event binding is built on top of the events defined
in the DOM objects.
93
3. _____ are used to represent the presentation layer which is provided to the end
users.
A. Model C. Controller
B. View D. Server
4. The ______ represents the layer that has the business logic
A. Model C. Controller
B. View D. Layer
8. _____ takes any integers, strings, arrays, and date as input separated with | to be
converted in the format as required and display the same in the browser.
A. looping C. pipes
B. comments D. var
9. A pipe can accept any number of optional parameters to output is known as_____
A. parameter pipe C. buil-in pipes
B. custom pipe D. pipe
10. Create a new ts file which you want to use as pipe is a part of____.
A. parameter pipe C. built-in pipes
B. custom pipe D. pipe
94
3.9 CHECK YOUR PROGRESS:POSSIBLE ANSWER
1. reactive 6. Classes
2. Model View Controller 7. Filters
3. View 8. pipes
4. Controller 9. parameter pipe
5. Document Object Model 10. custom pipe
3.10 ASSIGNMENTS
95
Unit 4: Angular Directives
4
Unit Structure
4.1 Learning Objectives
4.9 Assignments
96
4.1 LEARNING OBJECTIVES
After studying this chapter, students should be able to understand:
What is Directives and how useful in angular app.
How to use the directives.
The use of Ngif, Ngfor and Ngswitch with example.
How to create a different CSS files to define the style in HTML.
4.2 INTRODUCTION
97
1. Components directives directives with a template, how the component
should be processed, instantiated and used at runtime..
2. Structural directives change the DOM layout by adding and removing DOM
elements. It is denoted by using * sign.
3. Attribute directives change the appearance or behavior of an element,
component, or another directive.
A root component is the first Angular component that gets bootstrapped when
the application runs. Two things are special about this component:
98
Added to the bootstrap array of the module definition.
@Component({
selector: 'my-app',
template: `<h2>{{title}}</h2>
<p *ngIf="showElement">Show Element</p>
<div [ngSwitch]="inpvalue">
<p style='color:blue' *ngSwitchCase="1">You have selected Aadhar Card</p>
<p style='color:blue' *ngSwitchCase="2">You have selected Passport</p>
<p style='color:blue' *ngSwitchCase="3">You have selected Voter ID</p>
<p style='color:red' *ngSwitchDefault>Sorry! Invalid selection....</p>
99
</div>`
})
Output
NgIf
NgFor
NgSwitch
NgIf
100
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<div style='color:blue' *ngIf="true">You can See Passport....</div>`
})
Here If ngif= true the text will be visible on the web page.
NgFor
It is used to customize data display. It is mainly used for displaying a list of items
using repetitive loops.
App.component.ts file
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
})
export class AppComponent {
cust: any[] = [
{
code: '1001', name: 'Nirav', gender: 'Male',
total: 1255, dateOfBirth: '25/6/1990'
},
{
code: '1002', name: 'Pooja', gender: 'Female',
total: 1355, dateOfBirth: '9/6/1992'
101
},
{
code: '1003', name: 'Nishant', gender: 'Male',
total: 1455, dateOfBirth: '12/8/1995'
},
{
code: '1004', name: 'Neha', gender: 'Female',
total: 1555, dateOfBirth: '14/10/1989'
},
];
}
App.component.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
102
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table align="center" border="1" cellpadding="4" cellspacing="4">
<thead>
<tr>
<th style="background-color: Yellow;color: blue">Cust_Code</th>
<th style="background-color: Yellow;color: blue">C_Name</th>
<th style="background-color: Yellow;color: blue">C_Gender</th>
<th style="background-color: Yellow;color: blue">Total</th>
<th style="background-color: Yellow;color: blue">Date of Birth</th>
</tr>
</thead>
<tbody>
<tr *ngFor='let c of cust'>
<td>{{c.code}}</td>
<td>{{c.name}}</td>
<td>{{c.gender}}</td>
<td>{{c.total}}</td>
<td>{{c.dateOfBirth}}</td>
</tr>
</tbody>
</table>
</body>
</html>
103
Output
Ngswitch
A structural directive that adds or removes templates when the next match
expression matches the switch expression.
@Component({
selector: 'my-app',
template: `<h2>{{title}}</h2>
<div [ngSwitch]="inpvalue">
<p *ngSwitchCase="1">Monday</p>
<p *ngSwitchCase="2">Tuesday</p>
<p *ngSwitchCase="3">Wednesday</p>
<p *ngSwitchDefault>Sorry Invalid selection!!</p>
</div>`
})
export class AppComponent {
104
inpvalue: number = 1;
}
Output
NgStyle: Based on the component state, dynamic styles can be set by using
NgStyle. Many inline styles can be set simultaneously by binding to NgStyle.
NgClass: It controls the appearance of elements by adding and removing
CSS classes dynamically.
NgStyle
Ngstyle used to change the look and feel of elements.The NgStyle directive
lets you set a given DOM elements style properties. One way to set styles is by
using the NgStyle directive and assigning it an object literal.
<div [ngStyle]="{'background-color':'red'}"></<div>
This will change the div background color to red.
ngStyle is a very useful when its value is dynamic. The values in the object literal
that we assign to ngStyle can be javascript expressions which are evaluated and the
result of that expression is used as the value of the css property.
105
like this:
The above code uses the ternary operator to set the background color to green if
the persons country is the USA else red.But the be
inline, we can call a function on the component instead.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div [style.background-color]="'yellow'">
Uses fixed yellow background
</div>
</body>
</html>
Output
Another way to set fixed values is by using the NgStyle attribute and using key value
pairs for each property you want to set, like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
106
</head>
<body>
Here we are setting both the color and the background-color properties. But the real
power of the NgStyle directive comes with using dynamic values.
In our example, we are defining two input boxes with an apply settings button:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
107
</html>
This will apply the color and fontsize after apply button click on element.
NgClass
Src/style.css
.bordered {
border: 1px dashed black;
background-color: #eee; }
always having the border) and another one never having it:
componenet.html
<div [ngClass]="{bordered: false}">This is never bordered</div>
<div [ngClass]="{bordered: true}">This is always bordered</div>
108
Components directives directives with a template, how the component
should be processed, instantiated and used at runtime..
Structural directives change the DOM layout by adding and removing DOM
elements. It is denoted by using * sign.
Attribute directives change the appearance or behavior of an element,
component, or another directive.
The component directive is used to specify the template/HTML for the Dom
Layout.
The structural directive is used to add or remove the HTML Element in the
Dom Layout, typically by adding, removing, or manipulating elements... Its
built-in types are *NgIf,*NgFor,*NgSwitch. Structural directives are easy to
recognize by using an asterisk (*).
The attribute directive changes the appearance or behavior of a DOM
element. These directives look like regular HTML attributes in
templates(Ngstyle,Ngclass)
109
5. app.component.css: contains all the ______ for the component.
A. html file C. css style
B. ts file D. confing file
7. ____is used to create or remove a part of the DOM tree depending on a condition.
A. ngif C. ngstyle
B. ngswitch D. ngfor
9. app.component.ts: contains all the _____ used by the component to control its
behavior.
A. html C. code
B. ts D. css
1. Directives 6. *
2. @ 7. ngif
3. Component 8. ngclass
4. Attribute 9. code
5. css style 10.Decorators
110
4.9 ASSIGNMENTS
1. What is directives?
2. Explain the component directive in detail with example.
3. Explain the Structurel directive in detail with example.
4. Explain the attribute directive in detail with example.
111
Unit 5: Working with Forms
5
Unit Structure
5.1 Learning Objectives
5.9 Assignments
112
5.1 LEARNING OBJECTIVES
5.1 INTRODUCTION
Forms are critical to any modern front-end application, and they're a feature
that we use every day, even if don't realize it. Forms are required for securely
logging in a user to the app, searching for all the available hotels in a particular city,
booking a cab, building a to-do list, and doing tons of other things that we are used
to. Some forms have just a couple of input fields, whereas other forms could have an
array of fields that stretch to a couple of pages or tabs.
Angular, being a full-fledged front-end framework, has its own set of libraries
for building complex forms. The latest version of Angular has two powerful form-
building strategies. They are:
Both the technologies belong to the @angular/forms library and are based on
the same form control classes. They differ remarkably in their philosophy,
programming style, and technique. Choosing one over the other depends on your
personal taste and also on the complexity of the form that you are trying to create. In
113
my opinion, you should try both the approaches first and then choose one that fits
your style and the project at hand.
The table below summarizes the key differences between reactive and template-
driven forms.
114
5.4 REACTIVE FORMS
Reactive forms are more powerful. They are more scalable, reusable, and
testable. If forms are a key part of your application, or you're already using reactive
patterns for building your application, use reactive forms.
To create a reactive form we have to import certain modules and need to generate
form controls. So for that follow the below steps.
To use the reactive forms in angular need to import ReactiveFormsModule from the
angular /forms package and add it to NgModules import array.(app.module.ts)
@NgModule({
115
declarations: [
AppComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The main class called FormControl class which used to define building blocks. For
the single form conrol import the FormControl class into your component class and
create a new instance to save as class property.
Once you created the control in the component class you must associated with form
control element in the template. Update the template with the form control using the
116
formControl binding provided by FormControlDirective included in
ReactiveFormsModule.(nameeditor.component.html)
<label>
Name:
<input type="text" [formControl]="name">
</label>
Powerful Reactive forms give you access to the form control state and value at a
point in time. Any one can manipulate the current state and value through the
component class or the component template. The following examples display the
value of the form control instance and change it.
Through the valueChanges observable where you can listen for changes in
the form's value in the template using AsyncPipe or in the component class
using the subscribe() method.
With the value property. which gives you a snapshot of the current value.
(name-editor.component.html)
<label>
Name:
<input type="text" [formControl]="name">
</label>
<p>
Value: {{ name.value }}
</p>
117
of the underlying AbstractControl class are used to control form state and determine
when to display messages when handling validation.
Methods are used to change the control values. Reactive forms have methods to
change a control's value programmatically, which gives you the flexibility to update
the value without user interaction. A form control instance provides a setValue()
method that updates the value of the form control and validates the structure of the
value provided against the control's structure. The following example adds a method
to the component class to update the value of the control to Angular using the
setValue() method.
(name-editor.component.ts)
@Component({
selector: 'app-name-editor',
templateUrl: './name-editor.component.html',
styleUrls: ['./name-editor.component.css']
})
export class NameEditorComponent implements OnInit {
constructor() { }
ngOnInit() {
}
updateName() {
this.name.setValue('Angular');
}
}
118
5.4.3 GROUPING FORMS CONTROL
Angular will provide the facility to group multiple controls. Form control can give the
access over single input field, a form group will provide the group of control access.
Each control in a form group instance is tracked by name when creating the form
group.
First need to Create a property in the component class named profileForm and set
the property to a new form group instance. To initialize the form group, provide the
constructor with an object of named keys mapped to their control.
For the profile form, add two form control instances with the names firstName and
lastName.
(profileeditor.component.ts)
@Component({
selector: 'app-profile-editor',
templateUrl: './profile-editor.component.html',
styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
profileForm = new FormGroup({
firstName: new FormControl(''),
119
lastName: new FormControl(''),
});
}
A form group tracks the status and changes for each of its controls, so if one of the
controls changes, the parent control also emits a new status or value change. The
model for the group is maintained from its members. After you define the model, you
must update the template to reflect the model in the view.
(profile-editor.component.html)
<form [formGroup]="profileForm">
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
The ProfileEditor component accepts input from the user, but in a real scenario you
want to capture the form value and make available for further processing outside the
component. The FormGroup directive listens for the submit event emitted by the
form element and emits an ngSubmit event that you can bind to a callback function.
Add an ngSubmit event listener to the form tag with the onSubmit() callback method.
120
(profile-editor.component.html)
<label>
First Name:
<input type="text" formControlName="firstName">
</label>
<label>
Last Name:
<input type="text" formControlName="lastName">
</label>
</form>
The onSubmit() method in the ProfileEditor component captures the current value of
profileForm. Use EventEmitter to keep the form encapsulated and to provide the
form value outside the component. The following example uses console.warn to log
a message to the browser console.
onSubmit() {
// TODO: Use EventEmitter with form value
console.warn(this.profileForm.value);
}
}
Displaying the component
To display the ProfileEditor component that contains the form, add it to a component
template.
121
(app.component.html)
<app-profile-editor></app-profile-editor>
Developing forms requires design skills (which are out of scope for this page),
as well as framework support for two-way data binding, change tracking, validation,
and error handling, Template driven forms are forms where we write logic,
validations, controls etc, in the template part of the code (html code). The template is
responsible for setting up the form, the validation, control, group etc. Template
driven forms are suitable for simple scenarios, uses two way data binding using the
[(NgModel)] syntax, easier to use though unit testing might be a challenge.
Code for creating a simple Template driven form. In this code we show how
template-driven forms in Angular can be created. This code uses the FormsModule
and NgModel directive to register form controls on an out NgForm.
(app.module.ts)
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, FormComponent],
122
bootstrap: [AppComponent]
})
export class AppModule {}
(app.component.ts)
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
export class AppComponent { }
Create a new component named form using below syntax inside app folder.
(app/form.component.ts)
123
<label>Street:</label>
<input type="text" name="street" ngModel>
</div>
<div>
<label>Zip:</label>
<input type="text" name="zip" ngModel>
</div>
<div>
<label>City:</label>
<input type="text" name="city" ngModel>
</div>
<button type="submit">Submit</button>
</form>
<pre>
{{form.value | json}}
</pre>
<h4>Submitted</h4>
<pre>
{{value | json }}
</pre>
`
})
export class FormComponent {
value: any;
submit(form) {
this.value = form;
}
}
124
(app.component,html)
<form-component></form-component>
Create one more ts file inside the app folder and set the below code for design using
the bootstrap.
platformBrowserDynamic().bootstrapModule(AppModule);
125
5.6 FORM VALIDATION
User Interface play the vital role in any apps. To give the dynamic look at the
app must have to forms in app. Forms are almost always present in any website or
application. Forms can be used to perform countless data-entry tasks such as
authentication, order submission or a profile creation.
Improve overall data quality by validating user input for accuracy and
completeness.To design a form is easy but it must be well maintained. That means a
form must be a validate form. Because forms are used to collection of information so
information must be a in correct format so forms are need to be a validated.
126
5.6.1 TEMPLATE DRIVEN VALIDATION
To add validation to a template-driven form, you add the same validation attributes
as you would with native HTML form validation. Angular uses directives to match
these attributes with validator functions in the framework.
Every time the value of a form control changes, Angular runs validation and
generates either a list of validation errors, which results in an INVALID status, or
null, which results in a VALID status.
You can then inspect the control's state by exporting ngModel to a local template
variable. The following example exports NgModel into a variable called name:
Code of example.
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
<div *ngIf="name.errors.forbiddenName">
Name cannot be dob.
</div>
</div>
127
Explanation of code
The most important part of application is form validation. To validate the Reactive
form component class become the main class. Instead of adding validators through
attributes in the template, you add validator functions directly to the form control
model in the component class. Angular then calls these functions whenever the
value of the control changes.
We can perform the validation on Reactive form in two ways, either using validators
functions or using built-in validators.
Validator functions
There are two types of validator functions: sync validators and async validators.
128
Built-in validators
129
Forms are mainly used to attract the user. Forms enhance the look of the
interface of app. Forms are the mainstay of business applications
Code for creating a simple Template driven form
To give the dynamic look at the app must have to forms in app. Forms are
almost always present in any website or application. Forms can be used to
perform countless data-entry tasks such as authentication, order submission
or a profile creation.
To add validation to a template-driven form, you add the same validation
attributes as you would with native HTML form validation.
To validate the Reactive form component class become the main class.
Instead of adding validators through attributes in the template, you add
validator functions directly to the form control model in the component class.
Angular then calls these functions whenever the value of the control changes.
5. _____ forms adding a simple form to an app, such as an email list signup.
A. Template C. Normal
B. Reactive D. A & B
6. _____ tracks the value and validation status of an individual form control.
A. FormArray C. FormValue
B. FormGroup D. FormControl
130
7.______ tracks the same values and status for an array of form controls.
A. FormArray C. FormValue
B. FormGroup D. FormControl
10. There are two types of validator functions: sync validators and _____ validators.
A. void C. empty
B. null D. asyn
1. Forms 7. FormArray
2. 2 8. ReactiveFormsModule
4. Reactive 9. ng generate component
5. Template comp_name
6. FormControl 10. async
5.10 ASSIGNMENTS
1. What is forms?
2. List the types of form in angular with definition.
3. Differentiate reactive form and template driven form
131
4. How to create reactive form explain in detail.
5. How to create template driven form explain in detail.
6. What is form validation.
7. Explain how to validate reactive form with validation functions.
132
Block-3
Working With IONIC
133
Unit 1: Setting up the
Environment for IONIC 1
Unit Structure
1.12 Learning Objective
1.15 Node.js
1.17
1.23 Activities
134
1.1 LEARNING OBJECTIVE
Node.js installation
CLI installation
recommended as the first choice by many developers. Ionic is popular for the
following reasons:
135
native platform. Ionic Native further simplifies the use of Cordova plugins
in Ionic apps.
Performs great on mobile devices. The Ionic team devotes great effort to
make it perform well on different platforms.
The current release version of Ionic framework is 4.0. Ionic 4 is the first version of
Ionic to be framework agnostic. Ionic Core is the set of components based on Web
Components. Ionic Angular is the framework binding of Ionic Core with Angular. This
book focuses on Ionic Angular with Angular 6.
Apart from the open source Ionic framework, Ionic also provides a complete solution
Ionic Pro for mobile app development, which includes the following products:
Ionic Creator Ionic Creator is a desktop app to create Ionic apps using
drag-and-drop. It helps nontechnical users to quickly create simple apps
and prototypes.
Ionic View Ionic View allows viewing Ionic apps shared by others
di app testing and demonstration.
Ionic Deploy Ionic Deploy performs hot updates to apps after they are
published to app stores.
Ionic Package Ionic Package builds Ionic apps and generates bundles
ready for p
manage local build systems and can use the cloud service instead.
Ionic Monitor Ionic Monitor can monitor apps and report runtime errors.
136
Ideas brainstorming. This is when we identify what kind of mobile apps
to build. It usually starts from vague ideas and expands to more concrete
solutions.
User experiences design. This is when all pages and navigation flows
are finalized, and we are now clear what exactly needs to be built.
1.4 NODE.JS
Node.js is the runtime platform for Ionic CLI. To use Ionic CLI, we first need to
install Node.js (https://nodejs.org/) on the local machine. Node.js is a JavaScript
on the desktop machines and servers. Ionic CLI itself is written in JavaScript and
executed using Node.js. There are two types of release versions of Node.js the
137
to use Node.js version 6 or greater, especially the latest LTS version (8.12.0 at the
time of writing).
Installing Node.js also installs the package management tool npm. npm is
used to manage Node.js packages used in projects. Thousands of open source
packages can be found in the npmjs registry (https://www. npmjs.com/). If you have
background with other programming languages, you may find npm is similar to
Apache Maven (https://maven.apache. org/) for Java libraries or Bundler
(http://bundler.io/) for Ruby gems.
Ionic CLI
After Node.js is installed, we can use npm to install the Ionic command- line
tool and Apache Cordova.
Note : You may need to have system administrator privileges to install these two
packages. For Linux and macOS, you can use sudo. For Windows, you can start a
command-
using sudo when possible, as it may cause permission errors when installing native
packages. treat this as the last resort. the permission errors usually can be resolved
by updating the file permissions of the node.js installation directory.
After finishing installation of Ionic CLI and Cordova, we can use the command ionic
to start developing Ionic apps.
You are free to use Windows, Linux, or macOS to develop Ionic 4 apps. Node.js is
supported across different operating systems. One major limitation of Windows or
Linux is that you cannot test iOS apps using the emulator or real devices. Some
open source Node.js packages may not have the same test coverage on Windows
as Linux or macOS. So they are more likely to have compatibility issues when
running on Windows. But this should only affect the CLI or other tools, not Ionic 4
itself.
138
After Ionic CLI is installed, we can run ionic info to print out current runtime
environment information and check for any warnings in the output; see Listing 1-1.
The output also provides detailed information about how to fix those warnings.
Ionic:
@angular-devkit/build-angular : 0.13.8
@angular-devkit/schematics : 7.3.8
@angular/cli : 7.3.8
@ionic/angular-toolkit : 1.5.1
System:
npm : 5.6.0
OS : macOS Mojave
You are free to use your favorite IDEs and editors when developing Ionic
apps. IDEs and editors should have good support for editing HTML, TypeScript, and
Sass files. For open source alternatives, Visual Studio Code
(https://code.visualstudio.com/) and Atom (https://atom.io/) are both popular choices
tools. For commercial IDEs, WebStorm (https://www. jetbrains.com/webstorm/) is
recommended for its excellent support of various programming languages.
Getting up and running with Visual Studio Code is quick and easy. It is a small
download so you can install in a matter of minutes and give VS Code a try.
139
Cross platform
VS Code is a free code editor which runs on the macOS, Linux and Windows
operating systems.
macOS
Linux
Windows
VS Code is lightweight and should run on most available hardware and platform
versions. You can review the System Requirements to check if your computer
configuration is supported.
Extensions
Keymaps - Vim, Sublime Text, IntelliJ, Emacs, Atom, Visual Studio, Eclipse
Extensions integrate into VS Code's UI, commands, and task running systems so
you'll find it easy to work with different technologies through VS Code's shared
interface.
2. Ionic 4 Snippets
4. TSLint
5. Peacock
140
7. Angular Language Service
8. Angular v7 Snippets
9. angular2-switcher
Next steps
Once you have installed and set up VS Code, these topics will help you learn more
about VS Code:
$ xcode-select p
If you see output like that below, then command-line tools have already been
installed.
/Applications/Xcode.app/Contents/Developer
$ xcode-select --install
141
After the installation is finished, you can use xcode-select p to verify.
To run Ionic apps on the iOS simulator using Ionic CLI, package ios-sim is required.
Another package ios-deploy is also required for deploying to install and debug apps.
You can install both packages using the following command.
Note: Android APi level 22 is required to run ionic apps. Make sure that the required
SdK platform is installed.
Stand-alone SDK tools is just a ZIP file; unpack this file into a directory and
Android platform or third-party libraries. You need to install the platform tools and at
least one version of the Android platform. Run android in tools directory to start
Android SDK Manager to install platform tools and other required libraries.
-tools
be
found by Ionic. Suppose that the SDK tools is unpacked into /Development/android-
sdk, then add /Development/ android-sdk/tools and /Development/android-
sdk/platform-tools to PATH environment variable. For Android Studio, the Android
SDK is installed into directory /Users/<username>/Library/Android/sdk.
To modify PATH environment variable on Linux and macOS, you can edit
~/.bash_profile file to update PATH as shown below. The PATH environment below
142
uses the Android SDK from Android Studio. You can replace it with another directory
if stand-alone SDK tools is used.
export PATH=${PATH}/:/Users/<username>/Library/Android/sdk/platform-tools \
: /Users/<username>/Library/Android/sdk/tools
To modify the PATH environment variable on Windows, you can follow the steps
below.
3 Click Environment Variables in the dialog and find PATH variable in the list,
then click Edit.
4 Append the path of tools and platform-tools directories to the end of PATH
variable.
A. Native B. Hybrid
143
2. Ionic used ________ to interact with native platform.
A. Angular B. Swift
A. 2.0 B. 2.5
C. 3.0 D. 4.0
A. React.js B. Node.js
C. Vue.js D. Angular.js
Answer
1. B 2. D 3. D
4. B 5. A 6. C
144
1.12 ACTIVITIES
Install NodeJS
Install all the required extension for IDE, So that development can be more
productive.
Setup Android
145
Unit 2: Developing First Mobile
Application 2
Unit Structure
2.1 Learning Objective
2.2 Introduction
2.10 WebView
2.14 Assignments
146
2.1 LEARNING OBJECTIVE
Debugging
2.2 INTRODUCTION
new Ionic apps. The easiest way to create Ionic apps is using Ionic CLI. Before we
can create Ionic 4 apps using Ionic CLI, we need to enable the feature project-
angular first by running the following command.
Apps are created using the command ionic start. Below is the syntax of using ionic
start.
The first argument of ionic start is the name of the new app, while the second
argument is the template name. We can also pass extra options after these two
arguments. If not enough arguments are provided, Ionic CLI can help you to finish
the setup interactively with prompts. Ionic CLI supports creation of projects of three
types. Project types are specified using the option --type, for example, --
type=angular.
147
$ ionic start --list
--no-deps Do not install npm dependencies. Useful when you only want to
explore the content of a project starter.
--no-link Skip the prompt about connecting the app with Ionic Dashboard.
--project-id Specify the slug for the app. The slug is used for the directory
name and npm package name.
--package-id Specify the bundle ID/application ID for the app. This is the
unique ID of the app when publishing to the Apple store or Goog
highly recommended to set this value when Cordova integration is enabled.
The value of this option should be in the reverse domain format, for example,
com. mycompany.myapp. If not specified, the default value io.ionic.starter is
used.
Blank App
This template blank only generates basic code for the app. This template should be
used when you want to start from a clean code base
148
$ ionic start blankApp blank
$ cd blankApp
$ ionic serve
This will open the browser with the preview of your app which will reload
automatically once you change anything inside your project.
Starters are constructed within the Ionic Starters repository by overlaying a starter
app onto a set of base files, constructing a compressed archive of the files, and
uploading it around the world. The Ionic CLI then downloads and extracts the starter
template archive and personalizes files for each new app.
Local Development
After a new app is created using ionic start, we can navigate to the app directory and
run ionic serve to start the local development server. The browser should
149
automatically open a new window or tab that points to the address
http://localhost:8100/. You should see the UI of this Ionic app. Ionic sets up
livereload by default, so when any HTML, TypeScript or Sass code is changed, it
automatically refreshes the page to load the page with updated code. There is no
need for a manual refresh.
The default port for the Ionic local development server is 8100. The port can be
configured using the option --port or -p. For example, we can use ionic serve -p 9090
to start the server on port 9090.
we have a typical Cordova project structure where we can install native plugins, and
create platform-specific project files.
150
Config Files
151
-
152
Cordova Files
Besides the config.xml in the root directory, the directories hooks, platforms, plugins,
and www are all managed by Cordova.
153
App Files
Environment Files
--
--
Skeleton Code
The template blank already includes some basic code. It has only one page.
154
-
155
- -
- -
- -
156
- -
- -
157
-
- -
- - - -
158
- -
159
2.5 WORKING WITH SIMULATOR/EMULATORS
device emulators.
Then we need to finish several tasks before building the app for Android.
Install Gradle. Gradle is the build tool for Android apps. Follow the official
instructions (https://gradle.org/install/) to install Gradle on your local machine.
Accept Android SDK licenses. Use the sdkmanager tool in Android SDK to
accept all SDK package licenses by running sdkmanager --licenses. The tool
sdkmanager can be found in the directory of <Android_Home>/sdk/ tools/bin.
Now the app can be built for the Android platform using the following command.
We can start the emulator and test the app; Ionic app running on the Android 8.1
emulator. If the emulator is not started, the following command will try to start it.
160
When running on the emulator, we can also use the option --livereload to enable
livereload, so the app refreshes automatically when the code changes.
Then the app can be built for iOS platform using the following command. If you just
installed Xcode, you may need to open Xcode to install additional components first.
Now you can start the emulator and test your app.
Running the code above will launch the default iOS emulator. If you want to use a
different emulator, you can use --target flag to specify the emulator name. To get a
list of all the targets available in your local environment, use the following command.
Then you can copy the target name from the output and use it in the command ionic
cordova emulate ios, see the code below to use the iPhone 8 with the iOS 11.3
emulator.
Using iOS or Android emulators to test and debug Ionic apps is not quite convenient
because emulators usually consume a lot of system resources and take a long time
to start or reload apps. A better alternative is to use Chrome browser for basic
testing and debugging. To open Chrome DevTools, you can open the Chrome
system menu and select More Tools Developer Tools. Once the developer tools
161
window is opened, you need to click the mobile phone icon on the top menu bar to
enable device mode. Then you can select different devices as rendering targets: for
example, Apple iPhone X or Nexus 6P.
For Android platform, when an Ionic app is running on the emulator or a real device,
we can use Chrome DevTools (https://developers.google.com/web/tools/chrome-
devtools/) to debug the running app. Navigate to chrome://inspect/#devices in
Chrome and you should see a list of running apps. Clicking inspect launches the
DevTools to inspect the running app. If you cannot see the app in the list, make sure
that the device is listed in the result of the command adb devices.
For an iOS platform, when an Ionic app is running on the emulator or a real device,
we can use Safari Web Inspector (https://developer.apple.com/safari/tools/) to debug
the running app. After opening Safari, in the Develop menu, you should see a menu
item like Simulator iPhone X - iOS 11.3 (15E217). This menu item has a subitem
called localhost - index. html. Clicking this menu item opens the Web Inspector for
debugging.
The Web View powers web apps in native devices. Ionic maintains a Web View
plugin for apps integrated with Cordova. The plugin is provided by default when
using the Ionic CLI. For apps integrated with Capacitor, the Web View is
automatically provided.
Ionic apps are built using web technologies and are rendered using Web Views,
which are a full screen and full-powered web browser.
Modern Web Views offer many built-in HTML5 APIs for hardware functionality such
as cameras, sensors, GPS, speakers, and Bluetooth, but sometimes it may also be
162
necessary to access platform-specific hardware APIs. In Ionic apps, hardware APIs
can be accessed through a bridge layer, typically by using native plugins which
expose JavaScript APIs.
The Ionic Web View plugin is specialized for modern JavaScript apps. For both iOS
and Android, app files are always hosted using the http:// protocol with an optimized
HTTP server that runs on the local device.
Emulators
o iOS
o Android
163
Debugging the platform
o iOS
o Android
Understanding webview
1. Command for ionic start <name> ____________, to create app with tabs.
A. blank B. tabs
C. super D. No possible
A. True B. False
A. config.xml B. package.json
C. angular.json D. ionic.config.json
A. config.xml B. package.json
C. angular.json D. ionic.config.json
A. Cordova B. Angular
C. Ionic D. Javascript
A. index.html B. index.js
C. package.json D. angular.json
A. index.html B. app.module.ts
C. app.component.ts D. app.html
164
8. The ___________ file contains the logic to bootstrap the Ionic app
A. app.ts B. index.html
C. main.ts D. app.component.ts
A. angular B. ionic
A. start B. build
C. compile D. serve
A. Chrome B. Safari
12. Ionic apps are built using web technologies and are rendered using
__________
A. Serve B. Server
1. A 2. A 3. B
4. D 5. A 6. A
7. B 8. C 9. C
165
2.14 ASSIGNMENTS
o iOS
o Android
166
Unit 3: Typescript 3
Unit Structure
3.1 Learning Objectives
3.2 Introduction
3.5 Functions
3.8 Assignments
167
3.1 LEARNING OBJECTIVE
Typescript
Variables
Decorators
Angular
3.2 INTRODUCTION
Building hybrid mobile apps with Ionic requires mostly front-end skills,
including HTML, JavaScript, and CSS. You should have basic knowledge of these
programming languages before reading this book.
Ionic Angular is
also the framework. Other than standard JavaScript, Ionic Angular uses TypeScript
(https://www. typescriptlang.org/) by default. This is because Angular uses
TypeScript by default. You are still fre
new programming language. But TypeScript is strongly recommended for enterprise
applications development. As the name suggests, TypeScript adds type information
to JavaScript. Developers with knowledge of other static-typing programming
languages, for example, Java or C#, may find TypeScript very easy to understand.
The official TypeScript documentation
(https://www.typescriptlang.org/docs/index.html) is a good starting point to learn
TypeScript.
The reason why TypeScript is recommended for Ionic apps development is because
TypeScript offers several benefits compared to standard JavaScript.
168
Compile-Time Type Checks
TypeScript code needs to be compiled into JavaScript code before it can run inside
called transpiling. During the compiling, the compiler does type checks using type
declarations written in the source code. These static type checks can eliminate
potential errors in the early stage of development. JavaScript has no static-typing
information in the source code. A variable declared with var can reference to any
type of data. Even though this provides maximum flexibility when dealing with
variables in JavaScript, it tends to cause more latent issues due to incompatible
types in the runtime. For most of the variables and function arguments, their types
when assigning a string to a variable that should only contain a number. This kind of
error can be reported by the TypeScript compiler in the compile time.
In the below example, the variable port represents the port that a server listens on.
Even though this varia
string 9090 to port in JavaScript. This error may only be detected in the runtime.
port = '9090';
However, the TypeScript code in below example declares the type of port is number.
The following assignment causes a compiler error. So developers can find out this
error immediately and fix it right away.
port = '9090';
169
Rich Feature Sets
Apart from the essential compile-time type checks, TypeScript is also a powerful
programming language with rich feature sets. Most of these features come from
current or future versions of ECMAScript, including ES6, ES7, and ES8. Using these
features can dramatically increase the productivity of front-
see the usages of these features in the code of the sample app.
With type information in the TypeScript source code, modern IDEs can provide
smart code complete suggestions to incre
also do refactoring for TypeScript code. Navigation between different files, classes,
or functions is easy and intuitive. Front- end developers can enjoy the same coding
experiences as Java and C# developers.
The key point of writing TypeScript code is to declare types for variables, properties,
and functions. TypeScript has a predefined set of basic types. Some of those types
come from JavaScript, while other types are unique in TypeScript.
3.4.1 BOOLEAN
Boolean type represents a simple true or false value. A Boolean value is declared
using type boolean in TypeScript.
isActive = true;
3.4.2 NUMBER
Numbers are all floating-point values in TypeScript. A number is declared using type
number in TypeScript. TypeScript supports decimal, hexadecimal, binary, and octal
literals for numbers. All these four numbers in the code below have the same
decimal value 20.
170
let p2: number = 0x14; // hexadecimal
3.4.3 STRING
String type represents a textual value. A string is declared using type string in
TypeScript. Strings are surrounded by double quotes (") or single
to the development team to choose whether to use double quotes or single quotes.
The key point is to remain consistent across the whole code base. Single quotes are
more popular because they are easier to type than double quotes that require the
shift key.
TypeScript also supports ES6 template literals, which allow embedded expressions
in string literals. Template literals are surrounded by backticks (`). Expressions in the
template literals are specified in the form of ${expression}.
let a: number = 1;
let b: number = 2;
null and undefined are special values in JavaScript. In TypeScript, null and
undefined also have a type with name null and undefined, respectively. These two
types only have a single value.
types. For example, the code below assigns null to the variable v with type string.
171
However, null values generally cause errors in the runtime and should be avoided
when possible. TypeScript compiler supports the option --strictNullChecks. When
this option is enabled, TypeScript compiler does a strict check on null and undefined
values. null and undefined can only be assigned to themselves and variables with
type any. The code above will have a compile error when strictNullChecks is
enabled.
3.4.5 ARRAY
Array type represents a sequence of values. The type of an array depends on the
type of its elements. Appending [] to the element type creates the array type. In the
code below, number[] is the type of arrays with numbers, while string[] is the type of
arrays with strings. Array type can also be used for custom classes or interfaces. For
example, Point[] represents an array of Point objects.
3.4.6 TUPLE
The elements of an array are generally of the same type, that is, a homogeneous
array. If an array contains a fixed number of elements of different types, that is, a
element types. In the code below, the tuple points has three elements with types
number, number, and string.
Tuples are useful when returning multiple values from a function because a function
can only have at most one return value. Tuples of two elements, a.k.a. pairs, are
commonly used. Be careful when using tuples with more than two elements,
because elements of tuples can only be accessed using array indices, so it reduces
the code readability. In this case, tuples should be replaced with objects with named
172
3.4.7 ENUM
Enum type represents a fixed set of values. Each value in the set has a meaningful
name and a numeric value associated with the name. In the code below, the value of
status is a number with value 1. By default, the numeric values of enum members
start from 0 and increase in sequence. In the enum Status, Status.Started has value
0, Status.Stopped has value 1, and so on.
below, enum values Read, Write, and Execute have their assigned values. The
value of permission is 3.
To convert an enum value back to its textual format, we can do the lookup by
treating the enum type as an array.
// -> 'Stopped'
3.4.8 ANY
Any type is the escape bridge from the TypeScript world to the JavaScript world.
When a value is declared with type any, no type checking is done for this value.
While type information is valuable, there are some cases when type information is
not available, so we need the any type to bypass the compile-time check. Below are
two common cases of using the type any.
173
Integrate with third-party JavaScript libraries. If TypeScript code uses a third-
party JavaScript library, we can declare values from this library as any to
bypass type checks for this li
for this kind of libraries, either by loading type definitions from community-
driven repositories or creating your own type definitions files.
In the code below, the variable val is declared as any type. We can assign a string, a
number, and a Boolean value to it.
3.4.9 VOID
return a value. The return type of the sayHello function below is void.
console.log('Hello');
void can also be used as a variable type. In this case, the only allowed
3.4.10 UNION
Union type represents a value that can be one of several types. The allowed types
are separated with a vertical bar (|). In the code below, the type of the variable
stringOrNumber can be either string or number.
stringOrNumber = 44;
stringOrNumber = 'Test';
174
Union types can also be used to create enum-like string literals. In the code below,
the type TrafficSignalColor only allows three values.
3.5 FUNCTIONS
As shown in below example, we only need to declare function types either on the
variable declaration side or on the function declaration side. TypeScript compiler can
infer the types from context information.
return str.length;
};
return v1 * v2;
Function types are useful when declaring high-order functions, that is, functions that
take other functions as arguments or return other functions as results. When
specifying types of functions used as arguments or return values, only type
information is required, for example, (string) => number or (number, number) =>
number
forEach is a high-order function that takes functions of type (any) => void as the
second argument.
175
iterator(item);
// -> Output 1, 2, 3
Arguments
A function can declare any number of formal parameters. When the function is
invoked, the caller can pass any number of actual arguments. Formal parameters
are assigned based on their position in the arguments list. Extra arguments are
ignored during the assignment. When not enough arguments are passed, missing
formal parameters are assigned to undefined. In the function body, all the arguments
can be accessed using the array-like arguments object. For example, using
arguments[0] to access the first actual argument. This flexibility of arguments
handling is a powerful feature and enables many elegant solutions with arguments
manipulation in JavaScript. However, this flexibility causes an unnecessary burden
on developers to understand. TypeScript adopts a stricter restriction on arguments.
The number of arguments passed to a function must match the number of formal
parameters declared by this function. Passing more or fewer arguments when
invoking a function is a compile- time error.
If a parameter is optional, we can add ? to the end of the parameter name, then the
function. Optional parameters must come after all the required parameters in the
therwise, there is no way to correctly assign
arguments to those parameters. For example, given a function func(v1?: any, v2:
We can
or the value is undefined, the parameter will use the default value. The parameter
timeout of function delay has a default value 1000. The first invocation of delay
176
function uses the default value of timeout, while the second invocation uses the
provided value 3000.
setTimeout(func, timeout);
Interfaces
Interfaces in TypeScript have two types of usage scenarios. Interfaces can be used
to describe the shape of values or act as classes contracts.
For example, a receiver function may accept an object that contains the properties
name, email, and age. After a later refactoring, the development team found that the
date of birth should be passed instead of the age. The caller code was changed to
pass an object that contains the properties name, email, and dateOfBirth. Then the
177
receiver code failed to work anymore. These kinds of errors can only be found in the
runtime if developers failed to spot all those places that rely on this hidden data
format contract during refactoring. Because of this potential code breaking,
developers tend to only add new properties while still keeping those old properties,
interface User {
name: string;
email: string;
age: number;
console.log(user.name);
processUser({
name: 'Alex',
email: '[email protected]',
age: 34,
});
Classes
178
Below example shows important aspects of classes in TypeScript. A class can be
abstract. An abstract class cannot be instantiated directly, and it contains abstract
methods that must be implemented in derived classes. Classes also support
inheritance. The members of a class are public by default. public, protected, and
private modifiers are supported with similar meanings as in other object-oriented
programming languages.
Classes can have constructor functions to create new instances. In the constructor
function of a subclass, the constructor of its parent class must be invoked using
super(). The constructor of Rectangle takes two parameters width and height, but
the constructor of the subclass Square takes only one parameter, so super(width,
width) is used to pass the same value width for both parameters width and height in
the Rectangle constructor function.
super();
this.width = width;
this.height = height;
area() {
179
constructor(width: number) {
super(width, width);
constructor(radius: number) {
super();
this.radius = radius;
area() {
console.log(rectangle.area());
// -> 20
console.log(square.area());
// -> 100
console.log(circle.area());
// -> 314.1592653589793
180
3.7 LET US SUM UP
Understanding Typescript
Understanding Function
3.8 ASSIGNMENTS
Try to implement the below diagram. It contain class, variable, and function.
181
Block-4
Advance of IONIC
182
Unit 1: Ionic UI Controls 1
Unit Structure
4.2 Introduction
4.3 Input
4.4 Labels
4.5 Checkbox
4.7 Selects
4.8 Toggles
4.9 Ranges
4.11 Toolbar
4.13 List
4.16 Activities
183
1.1 LEARNING OBJECTIVE
1.2 INTRODUCTION
standard HTML form elements like inputs, checkboxes, radio buttons and selects;
and components designed for mobile platforms, like toggles or ranges. Ionic
provides out-of-box components with beautiful styles for different requirements.
1.3 INPUT
The component ion-input is for different types of inputs. This component supports
the following properties.
type The type of the input. Possible values are text, password, email,
number, search, tel, or url. The default type is text.
clearInput Whether to show the icon that can be used to clear the text.
clearOnEdit Whether to clear the input when the user starts editing the text.
If the type is password, the default value is true; otherwise the default value is
false.
184
autocorrect Whether auto-correction should be enabled. The default value
is off.
autofocus Whether the control should have input focus when the page loads.
inputmode The hint for the browser for the keyboard to display.
minlength The minimum number of characters that the user can enter.
step The increment at which a value can be set. This property is used with
min and max.
multiple Whether the user can enter multiple values. It only applies when
the type is email or file.
185
Below is a basic sample of using ion-input.
1.4 LABEL
Labels can be used to describe different types of inputs. ion-label is the component
for labels. It supports different ways to position the labels relative to the inputs using
the property position.
floating - Labels will float above the inputs if inputs are not empty or have
focus.
We can add the property position to the ion-label to specify the position.
<ion-label floating>Username</ion-label>
1.5 CHECKBOX
The component ion-checkbox creates checkboxes with Ionic styles. It has the
following properties.
color - The color of the checkbox. Only predefined color names like primary
and secondary can be used.
186
ionChange Fired when the value has changed.
<ion-checkbox [(ngModel)]="enabled"></ion-checkbox>
Radio buttons can be checked or unchecked. Radio buttons are usually grouped
together to allow the user to make selections. A radio button is created using the
component ion-radio. ion-radio supports properties color, checked, and disabled with
the same meaning as the ion- checkbox. ion-radio also has a property value to set
the value of the radio button. ion-radio supports the event ionSelect that fired when
A radio buttons group is created by the component ion-radio-group, then all the
descendant ion-radio components are put into the same group. Only one radio
button in the group can be checked at the same time. It has the following properties.
color - The color of the radio-button. Only predefined color names like primary
and secondary can be used.
<ion-radio-group>
<ion-list>
<ion-list-header>
187
Traffic colors
</ion-list-header>
<ion-item>
<ion-label>Red</ion-label>
</ion-item>
<ion-item>
<ion-label>Green</ion-label>
</ion-item>
<ion-item>
<ion-label>Blue</ion-label>
</ion-item>
</ion-list>
</ion-radio-group>
188
1.7 SELECTS
The component ion-select is similar to the standard HTML <select> element, but its
UI is more mobile friendly. The options of ion-select are specified using ion-select-
option. If the ion-select only allows a single selection, each ion-select-option is
rendered as a radio button in the group. If the ion-select allows multiple selections,
then each ion-select-option is rendered as a checkbox. Options can be presented
using alerts or action sheets. Below are configuration options for ion-select.
interface The interface to display the ion-select. Possible values are alert,
popover, and action-sheet. The default value is alert.
<ion-select-option value="red">Red</ion-select-option>
189
Green
</ion-select-option>
<ion-select-option value="blue">Blue</ion-select-option>
</ion-select>
190
Multiple selections select
<ion-
<ion-select-option>IE</ion-select-option>
<ion-select-option selected>Chrome</ion-select-option>
<ion-select-option selected>Firefox</ion-select-option>
</ion-select>
191
Use action sheet to display
response">
<ion-select-option>Yes</ion-select-option>
<ion-select-option>No</ion-select-option>
<ion-select-option>Maybe</ion-select-option>
</ion-select>
192
1.8 TOGGLES
Like checkboxes, toggles represent Boolean values but are more user friendly on
the mobile platforms. ion-toggle supports the same properties and events as ion-
checkbox. See the code below for a sample of ion-toggle.
<ion-toggle [(ngModel)]="enabled"></ion-toggle>
1.9 RANGES
Range sliders allow users to select from a range of values by moving the knobs. By
default, a range slider has one knob to select only one value. It also supports using
dual knobs to select a lower and upper value. Dual knobs range sliders are perfect
controls for choosing ranges, that is, a price range for filtering.
min and max - Set the minimum and maximum integer value of the range.
The default values are 0 and 100, respectively.
step - The value granularity of the range that specifies the increasing or
decreasing values when the knob is moved. The default value is 1.
snaps - Whether the knob snaps to the nearest tick mark that evenly spaced
based on the value of step. The default value is false.
pin - Whether to show a pin with current value when the knob is pressed. The
default value is false.
To add labels to either side of the slider, we can use the property slot of the child
components of the ion-range. Labels can be texts, icons, or any other components.
193
Labels of ion-range
</ion-range>
<ion-label slot="start">Min</ion-label>
<ion-label slot="end">Max</ion-label>
</ion-range>
Double knobs
<ion-label slot="start">Low</ion-label>
<ion-label slot="end">High</ion-label>
</ion-range>
194
1.10 HEADER AND FOOTER
Header is a parent component that holds the toolbar component. It's important to
note that ion-header needs to be the one of the three root elements of a page.
Headers are fixed regions at the top of a screen that can contain a title label, and
left/right buttons for navigation or to carry out various actions.
Footer is a root component of a page that sits at the bottom of the page. Footer can
be a wrapper for ion-toolbar to make sure the content area is sized correctly.
<ion-header>
<ion-navbar>
<ion-title>Header</ion-title>
</ion-navbar>
<ion-toolbar>
<ion-title>Subheader</ion-title>
</ion-toolbar>
</ion-header>
<ion-content></ion-content>
<ion-footer>
<ion-toolbar>
<ion-title>Footer</ion-title>
</ion-toolbar>
</ion-footer>
1.11 TOOLBARS
A toolbar is a generic container for text and buttons. It can be used as a header,
sub-header, footer, or sub-footer. Toolbars are created using the component ion-
toolbar.
195
Buttons in a toolbar should be placed inside of the component ion-buttons. We can
use the property slot to configure the position of the ion-buttons inside of the toolbar.
start - Positioned to the left of the content in LTR, and to the right in RTL.
end - Positioned to the right of the content in LTR, and to the left in RTL.
<ion-app>
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button>
</ion-icon>
</ion-button>
</ion-buttons>
<ion-title>My App</ion-title>
<ion-buttons slot="end">
<ion-button>
</ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding>
196
App content
</ion-content>
</ion-app>
Cards are a great way to display important pieces of content, and are quickly
emerging as a core design pattern for apps. They are a great way to contain and
organize information, while also setting up predictable expectations for the user.
With so much content to display at once, and often so little screen realestate, cards
have fast become the design pattern of choice for many companies, including the
likes of Google, Twitter, and Spotify.
For mobile experiences, Cards make it easy to display the same information visually
across many different screen sizes. They allow for more control, are flexible, and
can even be animated. Cards are usually placed on top of one another, but they can
also be used like a "page" and swiped between, left and right.
Cards are created using the component ion-card. A card can have a header and
content that can be created using ion-card-header and ion-card-content,
respectively. Below example shows a simple card with a header and content.
<ion-card>
<ion-card-header>
Header
</ion-card-header>
<ion-card-content>
Card content
</ion-card-content>
</ion-card>
197
ion-card-subtitle adds a subtitle to the content. Below example shows a card with an
image and a title.
<ion-card>
<ion-card-content>
<img src="http://placehold.it/600x100?text=Item1">
<ion-card-title>Item 1</ion-card-title>
<ion-card-subtitle>Another item</ion-card-subtitle>
<p>
This is item 1.
</p>
</ion-card-content>
</ion-card>
1.13 LIST
Lists are one of the most common interface elements in mobile applications. They
are an efficient way to display lots of information in a small space and the act of
198
scrolling through a list is basically second nature for most mobile users. Facebook
uses a list for their news feed, as does Instagram and many others.
Given the importance of lists, the Ionic team have put a lot of effort into creating an
optimised list component that has smooth scrolling, inertia, acceleration and
deceleration, and everything
Both the list, which contains items, and the list items themselves can be any HTML
element.
Using the List and Item components make it easy to support various interaction
modes such as swipe to edit, drag to reorder, and removing items.
<ion-list>
<ion-item>
<ion-label>Apple</ion-label>
</ion-item>
<ion-item>
<ion-label>Apricots</ion-label>
</ion-item>
<ion-item>
<ion-label>Avocado</ion-label>
</ion-item>
<ion-item>
<ion-label>Banana</ion-label>
</ion-item>
<ion-item>
<ion-label>Blueberries</ion-label>
</ion-item>
</ion-list>
199
1.14 GRID LAYOUT
The grid is a powerful mobile-first flexbox system for building custom layouts. It is
composed of three units a grid, row(s) and column(s). Columns will expand to fill
their row, and will resize to fit additional columns. It is based on a 12 column layout
with different breakpoints based on the screen size.
In the item card, we need to display two or three buttons. These buttons should take
up the same horizontal space of the line. This layout requirement can be easily
archived by using the grid layout. The grid layout is implemented using the CSS3
flexbox layout (https://css- tricks.com/snippets/css/a-guide-to-flexbox/).
The grid layout uses three components: ion-grid, ion-row, and ion-col. ion-grid
represents the grid itself, ion-row represents a row in the grid, ion-col represents a
column in a row. Rows take up the full horizontal space in the grid and flow from top
to bottom. Horizontal space of a row is distributed evenly across all columns in the
row. Grid layout is based on a 12-column layout. We can also specify the width for
each column using attributes from col-1 to col-12. The number after col- is the
number of columns it takes in the 12-column layout, for example, col-3 means it
takes 3/12 of the whole width. By default, columns in a row flow from the left to the
right and are placed next to each. We can use the property offset-* to specify the
offset from the left side. We can the same pattern as in col-* to specify the offset, for
example, offset-3 and offset-6. Columns can also be reordered using attributes
push-* and pull-*. The attributes push-* and pull-* adjust the left and right of the
columns, respectively. The difference between offset-* and push-* and pull-* is that
offset-* changes the margin of columns, while push-* and pull-* change the CSS
properties left and right, respectively.
For the alignment of rows and columns, we can add attributes like align-items-start,
align-self-start, and justify-content-start to ion-row and ion-col. These attribute
names are derived from flexbox CSS properties and values. For example, align-
items-start means using start as the value of the CSS property align-items.
<ion-grid>
<ion-row>
<ion-col>
200
<ion-button expand="full">1</ion-button>
</ion-col>
<ion-col>
<ion-button expand="full">2</ion-button>
</ion-col>
<ion-col>
<ion-button expand="full">3</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button expand="full">4</ion-button>
</ion-col>
<ion-col>
<ion-button expand="full">5</ion-button>
</ion-col>
<ion-col>
<ion-button expand="full">6</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<ion-button expand="full">7</ion-button>
</ion-col>
<ion-col>
<ion-button expand="full">8</ion-button>
201
</ion-col>
<ion-col>
<ion-button expand="full">9</ion-button>
</ion-col>
</ion-row>
<ion-row>
<ion-col col-4>
<ion-button expand="full">0</ion-button>
</ion-col>
<ion-col col-8>
</ion-col>
</ion-row>
</ion-grid>
1.16 ACTIVITIES
With the help of ion-range create a RGB color screen value from 0 to 255.
202
Unit 2: Advanced Components 2
Unit Structure
2.1 Learning Objective
2.2 Introduction
2.4 Popover
2.5 Slides
2.6 Tabs
2.7 Menu
2.8 Loading
2.11 Activities
203
2.1 LEARNING OBJECTIVE
2.2 INTRODUCTION
When implementing those user stories for the app, we already use many Ionic built-
in components. There are still some Ionic components that are useful but not
included in the app. We are going to discuss several important components,
including action sheet, popover, slides, tabs, modal, and menu. After reading this
chapter, you should know how to use these components.
An action sheet is a special kind of dialog that lets user choose from a group of
-alert we mentioned before, but only buttons are
allowed in an action sheet. It can also be used as menus. An action sheet contains
an array of buttons. There are three kinds of buttons in action sheets: destructive,
normal, or cancel. This can be configured by setting the property role to destructive
or cancel. Destructive buttons usually represent dangerous actions, for example,
deleting an item or canceling a pending request. Destructive buttons have different
styles to clearly convey the message to the user, and they usually appear first in the
array buttons. Cancel buttons always appear last in the array buttons.
Just like alerts and loading indicators, there are two Ionic components for action
sheets. The component ion-action-sheet-controller is responsible for creating,
presenting, and dismissing action sheets. The component ion-action-sheet is the
actual component displayed to the user. Action sheets are created using the method
create() of ion-action- sheet-controller.
204
The method create() takes an options object with the following possible properties.
Each button in the of array of buttons is a JavaScript object with the following
possible properties.
role - The role of the button. Possible values are destructive, selected, and
cancel.
205
ionActionSheetDidDismiss - Emitted after the action sheet is dismissed.
actionSheet: HTMLIonActionSheetElement;
async chooseAction() {
backdropDismiss: true,
buttons: [ {
text: 'Remove',
role: 'destructive',
icon: 'trash',
handler: this.removeFile.bind(this),
}, {
text: 'Move',
icon: 'move',
handler: this.moveFile.bind(this),
}, {
text: 'Cancel',
role: 'cancel',
icon: 'close',
handler: this.close.bind(this),
}]
});
return this.actionSheet.present();
206
}
close() {
this.actionSheet.dismiss();
removeFile() {
moveFile() {
2.4 POPOVER
A popover floats on top of the current page. Popovers are created by wrapping
existing components. We use the method create() of the component ion-popover-
controller to create popovers. The method create() has only one parameter, which is
a JavaScript object containing the following properties.
component -
event - The click event object to determine the position of showing the
popover.
207
HTMLIonPopoverElement instance. This is how data is passed between the
component wrapped by the popover and the component that creates the popover.
Now we use an example to demonstrate how to pass data when using popovers;
see the example below. The component contains some text, and we want to use a
popover to change the font size. In the PopOverComponent, we use the injected
PopoverController instance to create a new HTMLIonPopoverElement. When
invoking create(), the component to show is FontSizeChooserComponent, and we
pass the current value of fontSize to the component in the componentProps. The
event object of the click event is passed as the value of the property event, so the
popover is positioned based on the position of the click event. If no event is passed,
the popover will be positioned in the center of the current view. We use present() to
show the popover. We then use onDidDismiss() to add a callback function to receive
the updated value of fontSize from the popover.
@Component({
selector: 'popover-example',
templateUrl: 'popover-example.html',
styleUrls: ['./popover-example.css']
})
component: PopoverComponent,
event: ev,
208
translucent: true
});
2.5 SLIDES
The slides component is a container for multiple views. The user can swipe or drag
between different views. Slides are commonly used for tutorials and galleries.
Slides are created using components ion-slides and ion-slide. ion- slides is the
container component for ion-slide components inside of it. When creating the ion-
slides, we can use the property options to configure it. Ionic slides uses Swiper as its
implemenation. The property options takes the same value as in the Swiper API
(http://idangero.us/swiper/api/). The property pager controls whether to show the
pagination bullets.
After the slides component is created, we can also programmatically control the slide
transitions using the following methods.
209
getPreviousIndex() - Get the index of the previous slide.
In below example, we create an ion-slides component with the reference variable set
to slides. It contains three ion-slide components.
<ion-slides #slides>
<ion-slide>
Slide 1
</ion-slide>
<ion-slide>
Slide 2
</ion-slide>
<ion-slide>
Slide 3
</ion-slide>
</ion-slides>
<div>
<ion-button (click)="prev()">Prev</ion-button>
<ion-button (click)="next()">Next</ion-button>
</div>
210
method componentOnReady returns a Promise that resolved when the component
is ready. The method isValid() is required to check whether the Slides component is
ready to use.
'@angular/core';
@Component({
selector: 'app-slides',
templateUrl: './slides.component.html',
styleUrls: ['./slides.component.css']
})
loaded = false;
slides: any;
ngOnInit() {
this.slides = this.slidesElem.nativeElement;
this.slides.componentOnReady().then(() => {
this.loaded = true;
});
prev() {
if (this.isValid()) {
this.slides.slidePrev();
next() {
211
if (this.isValid()) {
this.slides.slideNext();
isValid(): boolean {
212
2.6 TABS
Tabs are commonly used components for layout and navigation. Different tabs can
take the same screen estate, and only one tab can be active at the same time.
Tabs components are created using the component ion-tabs, while individual tabs
are created using ion-tab. ion-tabs supports the standard properties color and mode
and the following special properties.
tabbarLayout - The layout of the tab bar. Possible values are icon-top, icon-
start, icon-end, icon-bottom, icon-hide, title-hide.
tabbarPlacement - The position of the tab bar. Possible values are top and
bottom.
tabbarHighlight - Whether to show a highlight bar under the selected tab. The
default value is false.
Once ion-tabs is created, we can get the ion-tab instance of this component. The
component ion-tabs instance provides different methods to interact with the tabs.
213
tabsHideOnSubPages - Whether the tab is hidden on subpages.
ion-t
In the template file below, we create an ion-tabs with the reference name set to tabs.
Each ion-tab has its title and icon. The first tab has a button to go to the second tab.
Tab One
</ion-tab>
Tab Two
</ion-tab>
Tab Three
</ion-tab>
</ion-tabs>
In the TabsComponent below,we use the decorator @ViewChild to get the reference
to the ion-tabs element and use its method select() to select the second tab.
'@angular/core';
@Component({
selector: 'app-tabs',
templateUrl: './tabs.component.html',
styleUrls: ['./tabs.component.css']
214
})
tabs: any;
constructor() { }
ngOnInit() {
this.tabs = this.tabsElem.nativeElement;
gotoTab2() {
this.tabs.select(1);
2.7 MENU
215
swipeEnable(shouldEnable, menuId) - Enable or disable the feature to
swipe to open the menu.
We create two menus at the start and end side. The ion-menu-button toggles the
menu at the start side. If the property contentId is not specified for the ion-menu, it
looks for the element with the attribute main in its parent element as the content.
<ion-app>
<ion-menu side="start">
<ion-header>
<ion-toolbar>
<ion-title>Start Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
216
<ion-menu side="end">
<ion-header>
<ion-toolbar>
<ion-title>End Menu</ion-title>
</ion-toolbar>
</ion-header>
</ion-menu>
<div main>
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-menu-button menu="start">
<ion-icon name="menu"></ion-icon>
</ion-menu-button>
</ion-buttons>
<ion-title>App</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
Content
</ion-content>
</div>
</ion-app>
The MenuComponent uses MenuController to open the menu at the end side.
217
import { Component } from '@angular/core';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
openEnd() {
this.menuCtrl.open('end');
2.8 LOADING
An overlay that can be used to indicate activity while blocking user interaction. The
loading indicator appears on top of the app's content, and can be dismissed by the
app to resume user interaction with the app. It includes an optional backdrop, which
can be disabled by setting showBackdrop:false upon creation.
Creating
218
Dismissing
The loading indicator can be dismissed automatically after a specific amount of time
by passing the number of milliseconds to display it in the duration of the loading
options. To dismiss the loading indicator after creation, call the dismiss() method on
the loading instance. The onDidDismiss function can be called to perform an action
after the loading indicator is dismissed.
cssClass - Additional classes to apply for custom CSS. If multiple classes are
provided they should be separated by spaces.
Events:
219
import { Component } from '@angular/core';
@Component({
selector: 'loading-example',
templateUrl: 'loading-example.html',
styleUrls: ['./loading-example.css']
})
async presentLoading() {
message: 'Hellooo',
duration: 2000
});
await loading.present();
console.log('Loading dismissed!');
async presentLoadingWithOptions() {
spinner: null,
duration: 5000,
220
translucent: true,
});
A. nullCheck B. strictNullChecks
C. nullNotAllowed D. noNullAllowed
3. let strings: = ['1', '2', '3'] will create ________ kind of array
A. number B. char
C. string D. letter
A. fixed B.variable
C. alike D.same
5. __________ type is the escape bridge from the TypeScript world to the
JavaScript world
A. Free B. Zone
C. NoRule D. Any
221
6. Void means ______ type
A. no B. null
C. undefined D. nil
A. ES6 B. Compiler
C. Microsoft D. Google
1. A 2. B 3. C
4. A 5. D 6. A
7. A
2.11 ACTIVITIES
222
Unit 3: Advanced Topics in
IONIC 3
Unit Structure
3.1 Learning Objective
3.2 Platform
3.3 Themes
3.4 Storage
3.5 Publish
3.8 Activities
223
3.1 LEARNING OBJECTIVE
3.2 PLATFORM
We have class Platform. It can be used to interact with the underlying platform. We
used the method ready() of Platform to wait for the Cordova platform to finish
initialization. The class Platform also has other methods.
versions() Gets version information for all the platforms. When running on
the iPhone emulator, the return value of versions() is [{"name":"iphone"},
{"name":"ios", "settings":{"mode":"ios","tabsHigh
light":false,"statusbarPadding":false,"keyboard
Height":250,"isDevice":true,"deviceHacks":true}}].
224
isPortrait() and isLandscape() Checks if the app is in portrait or landscape
mode, respectively.
ready() This method returns a promise that is resolved when the platform is
ready and we can use the native functionalities. The resolved value is the
name of the platform that was ready.
url()
There are three important EventEmitters in the Platform that are related to app
states. The EventEmitter pause emits events when the app is put into the
background. The EventEmitter resume emits events when the app is pulled out from
the background. These two EventEmitters are useful when dealing with app state
changes. The EventEmitter resize emits events when the browser window has
changed dimensions.
3.3 THEMING
Theme support is baked right into Ionic apps. Changing the theme is as easy as
updating the $colors map in your src/theme/variables.scss file:
$colors: (
primary: #488aff,
secondary: #32db64,
danger: #f53d3d,
light: #f4f4f4,
dark: #222
);
The fastest way to change the theme of your Ionic app is to set a new value for
primary, since Ionic uses the primary color by default to style most components.
not be removed.
225
Ionic provides different look and feels based on the current platform. The styles are
grouped as different modes. Each platform has a default mode that can also be
md for Material Design styles, ios for iOS styles. The platform ios uses the mode ios
by default, and other platforms use the mode md by default.
Ionic uses modes to customize the look of components. Each platform has a default
mode, but this can be overridden. For example, an app being viewed on an Android
platform will use the md (Material Design) mode. The <ion-app> will have
class="md" added to it by default and all of the components will use Material Design
styles.
ios Ios Viewing on an iphone, ipad, or ipod will use the iOS styles.
android Md Viewing on any android device will use the Material Design
styles.
core Md Any
use the Material Design styles.
Each Ionic component has up to three stylesheets used to style it. For example, the
tabs component has a core stylesheet that consists of styles shared between all
modes, a Material Design stylesheet which contains the styles for the md mode, an
iOS stylesheet for the ios mode, and a Windows stylesheet for the wp mode. Not all
components are styled differently for each mode, so some of them will only have the
core stylesheet, or the core stylesheet and one of the mode stylesheets.
226
You can use the class that is applied to the ion-app to override styles. For example,
if you wanted to override all buttons in Material Design (md) mode to have
capitalized text:
Once the mode is selected for the app, the html element will have the attribute mode
set to the mode name, for example, <html mode="ios">. The element <ion-app> will
have the mode name as a CSS class name, for example, <ion-app class="md"> for
the mode md. This class name can be used to override styles for different modes. In
the code below, we add extra styles only for the mode md.
.md {
font-size: 16px;
.md .button {
text-transform: capitalize;
.button-md {
text-transform: capitalize;
Ionic components have the property mode to set the mode. This mode overrides the
<ion-app>
<ion-header>
<ion-toolbar>
<ion-title>Range</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
227
<ion-label slot="start">md</ion-label>
</ion-icon>
</ion-icon>
</ion-range>
</ion-item>
<ion-item>
<ion-label slot="start">ios</ion-label>
</ion-icon>
</ion-icon>
</ion-range>
</ion-item>
</ion-list>
</ion-content>
</ion-app>
Ionic has different Sass variables to configure the styles. These variables can be
overridden in the file src/theme/variables.scss. For example, the variable $button-
md-font-size configures the button font size of mode md. The default value is 14px.
$button-md-font-size: 16px;
228
3.4 STORAGE
To storage data in app, and so the user can access all the data across different
different devices.
For this kind of data, we can store the data on the device. In this case, we can use
the key/value pairs storage provided by Ionic. The package @ionic/storage is
already installed as part of the starter template, so we can use it directly.
The storage stores key/value pairs. The value of each pair can be data of any type.
rialized to a JSON string before saving.
When the data is retrieved, the JSON string is deserialized back to a JavaScript
object. The Ionic storage package wraps the localForage library
(https://github.com/localForage/localForage). It provides a common API to access
different storage engines, including SQLite, IndexedDB, WebSQL, and localstorage.
The actual engine used in the runtime depends on the availability of the platform.
We use the class Storage from @ionic/storage to interact with the underlying
storage engine. The module created by IonicStorageModule. forRoot() should be
imported. The instance of class Storage can be injected into components. Storage
has the following methods.
229
forEach(callback) Invokes the callback function for each key/value pair in
the store.
Most of the operations in Storage are asynchronous. The return values of methods
get(), set(), remove(), and clear() are all Promise objects that resolved when the
operations are completed. In below example, we use set() to set the value first, then
use get() to read the value and assign it to the property value.
@Component({
selector: 'app-page-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
value: any;
ngOnInit() {
const obj = {
name: 'Alex',
email: '[email protected]'
};
this.storage.set('value', obj)
230
The method IonicStorageModule.forRoot() accepts an optional object to configure
the storage engine. This object has the following properties.
driverOrder - The array of driver names to test and use. The default value is
['sqlite', 'indexeddb', 'websql', 'localstorage'].
3.5 PUBLISH
Before the app can be published, we need to replace the default icons and splash
screens. Ionic can generate icons and splash screens from source images to create
images of various sizes for each platform. We only need to provide an image for the
icon and another image for the splash screen, then Ionic can generate all necessary
images. Source images can be .png file, .psd file from PhotoShop or .ai file from
Adobe Illustrator.
For icons, the source image should be file icon.png, icon.psd or icon.ai in the
directory resources of the Ionic project. The icon image should have a size of at
least 192 x 192 px without the round corners. For splash screens, the source image
should be file splash.png, splash.psd or splash.ai in the directory resources. The
splash screen should have a size of at least 2732 x 2732 px with the image centered
in the middle.
We use the command ionic resources to generate those resource files for icons and
splash screens.
231
// Icons only
$ ionic resources
Generated icons and splash screens are saved to the subdirectory ios and android
of the directory resources.
We can deploy the app to a device for testing. For iOS, open the generated project
in the directory platforms/ios with Xcode and use Xcode to deploy to the device. For
Android, open the generated project in the directory platforms/android with Android
Studio to deploy to the device.
Ionic CLI commands ionic run ios and ionic run android can also be used to deploy
apps to the device.
Ionic Deploy
release new versions to the users. Usually, these new versions need to go through
the same review process as the first version, which may take a long time to finish.
This can delay the delivery of new features and bug fixes. For Cordova apps, since
live updates without installing new versions. These static files can be replaced by the
wrapper to update to the new versions. Ionic Pro provides the deploy service to
perform live deployments.
Pro, we need to create a new app in the dashboard and link the app to Ionic Pro.
Because we already created the Ionic app, the following command is used to link it.
You can find the app_id in the dashboard.
232
$ ionic link --pro-id <app_id>
Ionic Pro uses a Git-based workflow to manage app updates. The command ionic
link will prompt to set up the Git repository. Just follow the instructions displayed
when running ionic link to finish the setup. Here we use Ionic Pro as the Git
repository. A new Git remote called ionic is added to the repository, and we can
push the current code to this remote. After the link, the file ionic.config.json is
updated to include the property pro_id.
In the Ionic Pro dashboard for the app, go to the tab Code and select Channels. Two
channels Master and Production have already been created. Master channel is for
binaries for development, while Production channel is for binaries for app stores.
Clicking the button Set up deploy next to a channel shows a dialog with instructions
on how to set up the deploy. There are three options of how updates are installed.
completely closed state. It will download the update in the background when
the user is using the app. The update is applied when the app is closed and
opened the next time.
closed state. It will wait on the splash screen until the update is downloaded
and applied. This mode forces users to always use the latest version.
update process is managed by you using the plugin API. This is not
recommended as it may break the app with broken updates. Using
e as the updates in these two
modes are done in the native layer.
We are going to use the background mode for the app. The dialog already shows
the command to run to install the plugin cordova-plugin- ionic.
--variable APP_ID="<app_id>" \
--variable CHANNEL_NAME="Master" \
--variable UPDATE_METHOD="background"
233
After a commit is pushed to the Git repository, a new build will run. You can check
the builds in the tab Builds. For each build, it can be manually deployed to a
channel. A channel can also be configured to auto- deploy builds in a Git branch.
A. True
B. False
A. Yes
B. No
A. md B. ios
C. an D. wp
A. Oracle B. MS-Access
C. MongoDB D. SQLite
A. clear() B. removeAll()
C. remove() D. deleteAll()
1. A 2. A 3. A
4. D 5. A
234
3.8 ACTIVITIES
Create a app and assign Splash Screen and Icon for Specific Platform
Create a app and use Primary and Secondary color for changing the Button
and App Background
235