100% found this document useful (1 vote)
55 views116 pages

Getting Started With Angular 2nd Edition Stephen Adams Download

The document provides information about the book 'Getting Started With Angular 2nd Edition' by Stephen Adams, which is available for download in PDF format. It includes details about the book's content, structure, and chapters, covering various aspects of Angular development. The book is published by Leanpub and aims to empower readers with practical knowledge about Angular and its applications.

Uploaded by

tjwhspe708
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
55 views116 pages

Getting Started With Angular 2nd Edition Stephen Adams Download

The document provides information about the book 'Getting Started With Angular 2nd Edition' by Stephen Adams, which is available for download in PDF format. It includes details about the book's content, structure, and chapters, covering various aspects of Angular development. The book is published by Leanpub and aims to empower readers with practical knowledge about Angular and its applications.

Uploaded by

tjwhspe708
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 116

Getting Started With Angular 2nd Edition Stephen

Adams pdf download

https://textbookfull.com/product/getting-started-with-angular-2nd-edition-stephen-adams/

★★★★★ 4.7/5.0 (49 reviews) ✓ 87 downloads ■ TOP RATED


"Perfect download, no issues at all. Highly recommend!" - Mike D.

DOWNLOAD EBOOK
Getting Started With Angular 2nd Edition Stephen Adams pdf
download

TEXTBOOK EBOOK TEXTBOOK FULL

Available Formats

■ PDF eBook Study Guide TextBook

EXCLUSIVE 2025 EDUCATIONAL COLLECTION - LIMITED TIME

INSTANT DOWNLOAD VIEW LIBRARY


Collection Highlights

Getting Started with Kubernetes 2nd Edition Baier

Getting Started with PhantomJS Beltran Aries

Getting Started with R: An Introduction for Biologists 2nd


Edition Andrew Beckerman

Getting Started with Gulp - Second Edition Travis Maynard


Make Getting Started with Processing py Allison Parrish

Getting Started with EEG Neurofeedback John N. Demos

Getting Started with Advanced C# 1st Edition Vaskaran


Sarcar [Sarcar

Getting Started with Microsoft System Center Operations


Manager Kevin Greene

Getting Started with Natural Language Processing MEAP V06


Ekaterina Kochmar
Getting Started With Angular
Stephen Adams
This book is for sale at http://leanpub.com/getting-started-with-angular

This version was published on 2020-04-01

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

© 2019 - 2020 Stephen Adams


Tweet This Book!
Please help Stephen Adams by spreading the word about this book on Twitter!
The suggested hashtag for this book is #gettingstartedwithangular8.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
#gettingstartedwithangular8
I thank my wife, Caroline, and children, Georgia and Charlie, who have supported and encouraged
me throughout writing this book.
Contents

Chapter 1: What is Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


What is Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Some examples of the type of projects built with Angular . . . . . . . . . . . . . . . . . . . . 2
Angular’s history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Why use Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Features of Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
The Client Contacts Manager Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Chapter 2: Angular Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


Overview of Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Installing the Angular CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Installing Visual Studio Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
The architecture of an Angular app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
The architecture of our Client Contacts application . . . . . . . . . . . . . . . . . . . . . . . . 27
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

Chapter 3: Getting Started with the Angular CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . 31


How a CLI helps Angular developers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Installing the Angular CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Creating the Client Contacts Manager application . . . . . . . . . . . . . . . . . . . . . . . . . 32
Running your application in the browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Commands of the Angular CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
What are Schematics? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Chapter 4: Components, Templates, and Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47


Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
What are components? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Why do we have components now? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
The structure of a component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
The Component class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
The component life cycle hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Passing data into and out of components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
CONTENTS

Component templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Categories of components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
An introduction to forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Creating a Reactive form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
When to use template forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
When to use Reactive forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Chapter 5: NgModules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
What are modules in Angular? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
The parts of the NgModule file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
How to create modules using the CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Creating modules for our Client Contact Manager application . . . . . . . . . . . . . . . . . 89
Adding our Client components to the ClientModule . . . . . . . . . . . . . . . . . . . . . . . 92
Adding Angular Material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Chapter 6: Routing and Navigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103


What are routes? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Creating our navigation component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Route parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Route Guards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Implementing a Route Guard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125

Chapter 7: Dependency Injection, Services, and HttpClient . . . . . . . . . . . . . . . . . . . . 127


What is Dependency Injection? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
How does Angular handle Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . 129
Providers in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Services in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
A look at the services Angular provides . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
The HttpClient service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Features of the HttpClient API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Advanced features of HttpClient service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

Chapter 8: Observables and RxJs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152


Observables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
What is RxJs? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
Examples of Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
The Operator Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Subjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
How Angular uses RxJs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
CONTENTS

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

Chapter 9: State Management and NgRx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183


Defining state management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
The Redux library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Exploring NgRx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Example of a Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Example of an Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Example of the Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Example of Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
Effects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Installing NgRx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Further Reading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

Chapter 10: Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202


Testing and Test Driven Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Jasmine in action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Setup and tear down of tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
The Karma test runner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Taking a Test Driven Development approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Karma settings in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Running tests using the Angular CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
Writing tests in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
The TestBed class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
Examples of tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231

Chapter 11: Packaging Our Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232


Building a release version with the CLI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
The angular.json file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Ahead-of-Time compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Other various production optimisations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Making use of lazy loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Application size budget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Measuring performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Chapter 1: What is Angular?
Welcome to this book on Getting Started with Angular. Throughout this book, we will be exploring
Angular and how to get started building applications with Angular. We will be looking at topics
such as how to set up an Angular application and how to use the tools the Angular team provide
to begin developing an Angular application. We will look at the architecture of a typical Angular
application and how components and modules are used to build sections of the app. We will explore
ways data is accessed and passed in an app and what mechanisms Angular provides for managing
data.
We will also look at more advanced topics, such as observables and RxJS, testing, and packaging an
application for production. We will even take a look at the NgRx, which is a library for managing
state.
In this chapter, we will introduce Angular, what it is, and the reasons it is an ideal choice for web
application development, as well as go through the features of Angular and what’s in the latest
release, version 8.
I will also introduce the demo application we are going to be building throughout the book. So, to
recap, in this chapter, we will cover the following topics: - Why are we looking at Angular? - What is
Angular? - Some examples of the types of applications that can be built with Angular - The history
of Angular, how it was started, and what problems it aimed to solve What are the new features of
Angular - What is the demo application we will be building throughout this book

What is Angular?
According to the official Angular docs, Angular is a platform that makes it easy to build applications
with the web. Awesome, but what does that actually mean? Well, Angular is a web application
framework that helps developers build web applications, web applications that can run on all
platforms, from desktop and mobile, which makes Angular an ideal choice for your next web
application.
The official documentation goes on to describe Angular as, [combining] declarative templates, de-
pendency injection, end-to-end tooling, and integrated best practices to solve development challenges.
Angular empowers developers to build applications that live on the web, mobile, or the desktop.
This perfectly describes what Angular is. Through templates, dependency injection, and end-to-end
tooling, Angular empowers developers to build web applications and applications that are built on
best practices.
Chapter 1: What is Angular? 2

Some examples of the type of projects built with


Angular
By learning Angular, you can build many different types of applications, using the one framework.
For example, you can build a complete web application, such as the Google Grab and Go program,
where enterprise companies can manage their usage of Chromebooks.
Google announced the Grab and Go program for Chromebooks, powered by Angular at the
following URL: https://blog.angular.io/google- announces-grab-and-go-program-for-chromebooks-
powered-by-angular-7954c11900bd.¹
If you ever wanted to build an email client, you can in Angular. There is already a project called
ProtonMail, which is a full-featured email client developed by scientists and engineers from CERN,
written in Angular.
You can also build desktop applications in Angular. Working along with Electron (Electron | Build
cross-platform desktop apps with JavaScript, HTML, and CSS), the Node-based framework for
building cross-platform desktop apps, you can use Angular as the framework to structure your code
while letting Electron manage the running of the application on the desktop. A great example of this
type of project is Nrwl’s Angular Console application, which provides Angular developers with a
UI in order to work with the Angular CLI (more on the CLI later).
And, of course, there is mobile; through using projects such as Angular Material, you can create
Angular applications that are designed to look exactly like native mobile applications, (especially if
you are building for Android). Now, while Angular will allow you to create a web application that
looks and acts like it will run as a native application, Angular doesn’t solve the problem of how to
install the project as a native mobile application, along with the full native support of the phone’s
features. That’s where a project like Ionic comes in. But, as you can see, a developer who knows
how to write Angular applications has a lot of variety for the projects they can build.

Angular’s history
The history of Angular is an interesting one; first, there was AngularJS, and then came Angular.
AngularJS was created as part of an internal project within Google by Misko Hevery. He created
the first version of the project to make it easier for the designers within his team to build web
applications.
Misko wanted a way to extend the vocabulary of HTML in order for the designers to use HTML
tags that were more relevant to what they were designing. So, over a long weekend, yes, that’s a
weekend, Misko came up with the first version of AngularJS. The name Angular came from the
angled brackets that are at the beginning and the end of an HTML tag.
¹https:/ / blog. angular. io/ google-announces- grab- and- go- program- for- chromebooks- powered- by-angular- 7954c11900bd
Chapter 1: What is Angular? 3

Brad Green, Misko’s team leader at the time, asked Misko to work on a project called the Google
Feedback Tool, which was written in Google Web Kit (GWT), a Java-based framework. But, after
six months working on the project with GWT, the team found that it was extremely difficult to
work with. So, Misko said that he could rewrite the Feedback Tool project in two weeks using his
side project, AngularJS. Unfortunately, he took three weeks to complete the project, but he reduced
the number of lines of code down to 1,500 from the 17,000, which is the amount the old GWT version
had. And all this in three weeks as a solo developer!
Brad was obviously impressed, so he asked other developers to help Misko to work further on
Angular; Igor Minor (who still works on Angular along with Misko) and Shyam Seshadri both helped
Misko to complete the rewrite of the Google Feedback Tool and develop AngularJS further.
The next project the team worked on with AngularJS was the DoubleClick application that Google
had just purchased. The team was challenged to create a new landing page for DoubleClick; first,
they tried using GWT, but, after a two-week struggle, they turned to AngularJS, which Misko had
been promoting within Google. They were able to complete the landing page project within two
days using AngularJS. As a result of this success, the DoubleClick team decided to use AngularJS.
With this, the first version of AngularJS was released in May 2011.
But this is all about AngularJS; we’re not looking at the previous version. We’re interested in the
latest version of Angular, its second iteration. This new version of Angular came out in September
2016, after two and a half years of development, which shows how much thought has gone into the
new version.

Why use Angular?


Why should a developer decide to learn Angular? Well, there are several reasons, but the main
reason is so they can create applications for all platforms: desktop, mobile, and the web. All these
platforms are reachable for a developer who knows how to write Angular applications.
There are other similar technologies out there; for example, there are many JavaScript frameworks
like Angular, but Angular is extremely well established and supported by Google. It is an ideal
frontend framework for enterprise-level application, with all the out-of-the-box features that come
with Angular (including modules, classes, components, and unit testing), All of these are extremely
important to enterprises wanting their teams to develop well structured, tested applications;
applications that are going to work the first time for their clients.
There is also a huge ecosystem around Angular; teams such as Nrwl with their Nx Extensions,
which allow teams to create libraries to support the large enterprise-level applications that Nrwl
specialises in. There is also a vast amount of training resources available to an Angular developer;
companies such as Plurasight, EggHead, and Ultimate Angular all have in-depth courses for Angular
development.
There are a large number of reasons why we should use Angular as our web application framework
of choice. Let’s look at these reasons.
Chapter 1: What is Angular? 4

Supported by Google
One of the main reasons to use Angular is because it is supported by Google. They don’t just sponsor
the development of Angular, they are the team behind the development of Angular; Unlike other
frameworks, which are supported by open source developers who work on fixing issues and creating
new features for a framework in their spare time, Angular has a full-time team constantly working
on supporting Angular.
Google has also provided a Long Term Support (LTS) plan for Angular, which shows that they plan
to support older versions of Angular for the next few years. In this LTS, we can see what versions of
Angular they provide support for and when older versions will no longer be supported. With Google
being so transparent in terms of their support of Angular, we can be sure that it has a long future.
This is extremely important for large businesses looking to select the framework they are going to
invest in for their next large-scale project. Being able to see that Angular has the support of a large
organisation like Google, and that there is an LTS plan, which shows that Angular will be supported
for the long term, makes the decision to pick Angular as their framework of choice a straightforward
one.
See the release dates from the official Angular website: https://angular.io/guide/releases.²

Built on TypeScript
Angular is built on TypeScript, a superset of JavaScript, from Microsoft. TypeScript brings so many
benefits, including Type interfaces and static typing. When we create objects and variables within
our code through static typing, the details of these types are known when we compile our code
and this helps to provide insight. So, bugs can be found at compile time instead of runtime. Not
only does TypeScript help us write better code, but it also allows tools such as VSCode to provide
IntelliSense of our code, which gives us better navigation, refactoring, and autocompletion, making
the experience of writing TypeScript far more enjoyable than JavaScript.
Along with providing a great development experience, as a result of using TypeScript, we have access
to all the ES2016/ES2017 features that aren’t yet available in JavaScript. TypeScript can provide
features that are still to be released in JavaScript. Being able to compile down to ES2015 (the version
of JavaScript that the browser understands), TypeScript can provide these latest features and still be
able to generate ES2015 code.
So, being built on TypeScript, Angular has access to all the latest features of the language and all
the fantastic tooling TypeScript provides.

The Angular CLI


Another great reason for using Angular is the Angular CLI; this is a command-line tool provided
by the Angular team that helps us to build and run Angular projects. The CLI comes with a wide
²https:/ / angular.io/ guide/ releases
Chapter 1: What is Angular? 5

range of features, including the following: - Creating the start of a project - Creates components,
services, directives, and other files using a simple command - Runs the application in the browser -
Reloads the application after each saved change so that the latest version is displayed in the browser
- It can update a project’s dependencies (other libraries used in a project) automatically - It can add
new libraries to the project - It can run all the unit tests in a project and the end-to-end tests
The Angular CLI is a great tool, and you’ll see as we proceed that learning Angular is an important
part of developing Angular applications. Many other frontend frameworks don’t have CLIs, and
those that do, they do not have the features of the Angular CLI.

Command-Line Interface (CLI) is a way of writing commands to the computer via a


Terminal window.

Built on best practices


Angular is designed with best practices in mind. Any code generated by the CLI follows these best
practices, as set out by the team from Google. By following the approach prescribed by the Angular
team on how to write an Angular application, you know that the application you are building is
using the best practices of modern web applications.
These best practices include the following: - Component-based architecture - Modularised structure
- Dependency injection - Testing - Readable code - Ease of maintenance
Being built on a set of best practices means that you know the architecture of your application is
built on the basis of these good practices.

Testing is a first-class citizen of Angular


Testing is an extremely important part of creating bug-free applications. Angular supports testing
straight out of the box. Whenever the CLI creates a new Component or Service, it automatically
creates a Test Spec file for the new Component or Service. The CLI can also run the tests. No longer
do we have to set up test runner files; all of this is automatically managed by the CLI.
Making writing tests and running tests are so easy, so there is no reason not to have a good set of
tests for your application. Angular actively encourages writing tests, and by doing this, it reduces
bugs and issues that an end user may find, thereby making Angular an ideal choice for large-scale
enterprise level applications.

The Angular community


Another great reason for choosing Angular as your framework of choice is the community that
has grown around Angular. There are over 100,000 Angular developers, a number that is still
growing. There are Angular meetups all around the world, where you can go and meet other Angular
developers to discuss their experiences with using Angular and you can learn from them.
Chapter 1: What is Angular? 6

There are also many conferences you can attend as an Angular developer to learn about the
new features of Angular and hear talks on different approaches to working with Angular. These
conferences are all over the world, and attended by the Angular team, so you can put your questions
to the team directly.
Not only are there conferences and meetups you can attend to learn about Angular, but there
are also so many online resources created by members of the Angular community that we
can access to learn about Angular. There are sites such as Ultimate Courses (https:// ultimate-
courses.com/courses/angular³) who provide courses on Angular and TypeScript.
There are also podcasts where you hear interviews with leaders of the Angular community, including
the Angular team. Podcasts such as Adventures in Angular and EggHead.io provide great interviews
with Angular developers.

Access to third-party libraries


The Angular community, as well as allowing us to learn from one another, is also active in building
libraries and tools that work with Angular. Libraries such as NgRx, NGXS, and MobX all provide
solutions on how to manage state within an Angular application (NgRx is something we will
explore in Chapter 9, State Management and NgRx). There are also UI libraries such as Angular
Material, NGX-Bootstrap, and Nebular, which provide UI components you can add to your Angular
applications.
There are libraries for accessing data from cloud-based systems, such as Firebase. So, if your
application needs to connect to an existing Firebase application, there are libraries you can add
that simplify working with Firebase in your application. You can also find libraries that facilitate
working with GraphQL if that’s how your team creates their APIs.
If you want to add tools to your Angular workflow, the Angular community has provided tools
like Augury (https://augury.rangle.io⁴) from Rangle.io, which is a plugin for Chrome for debugging
Angular applications.
Another great tool from the Angular community is the NX workspaces from Nrwl. They have
created an extension to the Angular CLI that helps to create large enterprise Angular applications,
where teams of developers work on the same project. The NX tool helps the CLI create libraries
within Angular projects so that large-scale teams can share code across teams.

To see the types of extra resources available for Angular, look at the Resources list on the
Angular website: https://angular.io/resources.⁵

As you can see, there are so many reasons to use Angular. We’re already on version 8, which shows
that the Angular team aren’t slowing down in terms of making Angular better and better. Let’s now
go through some of the recent features of Angular and see what’s new in Angular.
³https:/ /ultimatecourses. com/ courses/ angular
⁴https:/ / augury. rangle. io
⁵https:/ / angular. io/ resources.
Chapter 1: What is Angular? 7

Features of Angular
As we know, Angular provides a framework for developing web applications, but there is more
to Angular than just the building blocks of a web application (components, services, directives,
and so on). Angular has many features we can use as Angular developers to create fast, powerful
applications.

Schematics
The first feature we’re going to look at is schematics. This is a tool we can add to our workflow as
Angular developers, similar to how we use the Angular CLI. Schematics allow us to apply transforms
to our projects; we see an example of this when we ask the Angular CLI to create Components or
Services for our application.
When we call the CLI to create a Component file, it updates the filesystem where our project is kept.
So, the CLI is writing to the filesystem. You’ll see as we progress through this book that the Angular
CLI is really helpful at starting up and adding to a project.
While the CLI is a wonderful workflow tool, the role of schematics is to build upon this scaffolding
feature that the CLI supports. So, schematics allow us to add to the project in a way that we can
get the CLI to build new features as part of our project. For example, we could write a schematic
that will add a new library to a project. Or, we could have a schematic that adds a UI library, which
is standard across all projects within an organisation, to a new Angular project. If your company
has a set of UI components that need to be used in any project, we could write a schematic, which
is called through the CLI, that will add this UI library and create the new Angular project in one
process.
Schematics don’t write to our filesystem; they update a Tree object. This Tree object is a represen-
tation of our project’s filesystem, and when a schematic is run, this Tree object is updated with the
new updates, as set out in the schematic’s rules.
A schematic is a TypeScript file that has the rules for this new schematic set out within this file. In
the schematic file, the Tree data object can be updated and added to. So, we can update the Tree to
have new files, or add new libraries.
Tools such as Nrwl’s NX workspaces make use of schematics to add to the workflow of the Angular
CLI. So, if your project is using the NX workspaces, you can run commands that create libraries that
will be shared across teams.

To read more about NX and how it makes use of schematics, check out the NX workspaces
website: https://nx.dev/getting-started/nx-and-cli⁶.
⁶https:/ / nx. dev/ getting- started/ nx- and- cli
Chapter 1: What is Angular? 8

CLI prompts
Another feature is CLI prompts, where the Angular CLI will ask questions when we run a command
such as ng add or ng generate (both commands we will see in use throughout the book). The CLI
will prompt the user with questions such as Which stylesheet format would you like to use? or Would
you like to add Angular routing?.
We can also create these prompts for our own schematics, so when a team member is running one
of our schematics through the Angular CLI, they will be prompted with questions we want them
to be asked as the schematic is running in order for them to make different choices in terms of the
features our schematic may be adding to the project it is building.
The great benefit of having CLI prompts is that it helps developers discover new features of the CLI.
With each release of the CLI, the team can add new prompts, asking if we want to make use of any
new features that are part of a new Angular release.

Angular Elements
A really interesting new feature of Angular is Angular Elements. Angular Elements is the ability to
create custom web components that can be loaded into any modern browser.
Through these web components, we can create small Angular applications, which will run as part
of the web page. For example, if you have a web page built using ASP.Net, but a small section of the
page needs to use a piece of functionality that is already in an Angular application, with Angular
Elements, you can convert that Angular application to a web component that will run within the
ASP.Net page as a standalone piece of functionality.
Web components are a feature of the Web Platform (https://www.w3.org/Talks/2012/10- lea-
webplatform/wpd-talk/#intro⁷) and are supported by all modern web browsers. They allow us, as
web developers, to extend HTML by creating our own tags, which the browser will understand.
We can package up HTML, CSS, and JavaScript to create one of these Web Components, which the
browser can understand and run, just like it would a standard HTML tag.
With Angular Elements, a Web Component made with HTML, CSS, and JavaScript can also have the
Angular framework incorporated into the component, giving us access to all that Angular provides.
This means our component can, in essence, be a mini-Angular application, running within any
other type of web page. So, if we have a React page that needs to have a feature from an Angular
application, it can be loaded via Angular Elements.
One area where I’ve found Angular elements to be extremely useful is when there is an AngularJS
application that needs upgrading to Angular (AngularJS will no longer be supported after 2021).
With Angular Elements, we can create new features for an existing AngularJS site and then load
this new feature into the AngularJS site using Angular Elements. Then, as the AngularJS code is
rewritten in Angular, each new part can be loaded into the original application via an Angular
Element. Once everything has been written in Angular, the AngularJS code can be removed and we
⁷https:/ / www. w3. org/ Talks/ 2012/ 10-lea- webplatform/ wpd- talk/ #intro
Chapter 1: What is Angular? 9

now have everything written in Angular. The end user will not notice a difference. Well, perhaps
the application will load faster for them, but that’s not a problem!

The Ivy Renderer


Another feature of Angular is the new view renderer engine called Ivy.
Ivy provides so many great features, including the following: - Easier-to-read generated code. - Faster
rebuild times between updates. - Small payload sizes, especially production-ready code. The smaller
the payload, the faster the application loads. - Improved Type checking in our HTML templates.
While Ivy is nearly ready, it’s not quite set for production-ready applications, so if you want to play
with it to see the great benefits it brings, then use the preceding command to create an application
that uses Ivy. Then, you’ll be able to see how much smaller the final size of the application Ivy
generates is and how fast it reloads between each build.
A great place to find out about Ivy is the Angular Next website, which is a guide with documentation
on some of the new features coming in Angular. You can find this guide by going to Angular Next
(https://next.angular.io/guide/ivy⁸).

CLI Builders
Another new feature in Angular is CLI Builders. This is a new API that allows us to add to, and
build upon, features with the Angular CLI.
We currently have schematics, which, as we know, allow us to write commands that the CLI can
use to generate new code for our applications. CLI Builders expands on this and provides an API we
can use to write commands to the CLI’s build system.
While schematics give us the ability to ask the CLI to generate new files or install new packages
for us, for example, adding Angular Material as part of a new application can be handled through
a schematic. With CLI Builders, the Angular team have expanded on this openness to the CLI and
have provided us with a way to write commands that can change the build system of Angular.
Through CLI Builders, we can run commands and tasks against the CLI to build our Angular
applications in any way we want. So, for example, as part of the build, we may need to have all
Angular Libraries built at the same time, or have all our tests run as part of the build; these tasks
can now be set up through the CLI Builder API.

Differential loading of JavaScript


In Angular, the CLI will now produce both ES5 and ES2015 JavaScript. ES5 is a legacy version of
JavaScript, while ES2015 is the latest version of JavaScript with all the modern features we now
expect of JavaScript. This will improve loading times in today’s modern browsers, as they will be
given the ES2015 version of the bundled code instead of the legacy ES5 version, which is far slower.
⁸https:/ / next. angular. io/ guide/ ivy
Chapter 1: What is Angular? 10

The Angular route improvements


Another new feature of Angular is the fact that the routing in our applications has been improved
to support AngularJS routing. By doing this, it will help with upgrading an AngularJS application
to Angular because the routing of an application is usually the last thing to be upgraded.
In Angular, there will be a backward compatibility mode for the router, so it will understand how to
run the AngularJS version of the router, and lazy-loading is supported for the AngularJS router. This
is a real benefit for those on AngularJS looking to upgrade before AngularJS is no longer supported.

Library updates
Along with all these new features in Angular, all the versions of RxJS, TypeScript, and Node have
been updated to their latest versions. So, we can start taking advantage of the new features from
these libraries as well.
Angular has some really nice new features; it is expanding in terms of opening up the Angular CLI
to us as developers so that we can tailor the CLI to our needs; it’s also adding features to help with
the upgrade from AngularJS to Angular.
The way we write Angular applications, which we will learn in this book, still applies to Angular 8,
so once you know how to create applications with Angular, you can then explore further these new
features in Angular.

The Client Contacts Manager Application


So, throughout this book, we are going to be building a sales team contacts app for a fictional
company. The idea behind this app is to have a system that allows the fictional sales team of our
fictional company to manage and access the contact details of their clients and the companies they
work with. This mini-CRM (Customer Relationship Manager) allows us to create an app that uses a
number of features so we can really explore the features of Angular. This application’s main features
are that it allows us to add, edit, and view the details of customers. We can also filter the list of
customers using the built-in features of Angular.
We can look at how we will create the UI using Angular components and Angular Material. We can
look at how we will build up the model of the application, how data will be passed throughout our
app as we build up the functionality to add new customers, save their details, and see a list of all of
our saved customer contacts.
We will see how Angular uses TypeScript, which gives us excellent tooling and insight into our code,
making the development process even easier than before when we were using JavaScript.
The idea is to create two versions of the mini-CRM that the salesperson will use; the mobile version
will be used when they are out and about talking to their customers, and the desktop app will be
used when back in the office to search for all the new wonderful customers they have.
Chapter 1: What is Angular? 11

As part of this application, we are going to use a fantastic third-party library called the In- Memory
Web API (https://github.com/angular/in-memory-web-api⁹). This library allows us to create local,
in-memory storage similar to a database that we can save data to, access data from, and remove data
from, all via API calls.
Using this library means we have a source of storage for our Client Contacts Manager Application
and we can make API calls to this storage system without having to set up a local database of external
API. We can just focus on learning how to write Angular.
Once you’ve finished reading this book, and you’ll want to create your own application to practice
what you’ve learned, I highly recommend looking at the In Memory Web API as a temporary data
source for your practice applications; it’s not a replacement for a real database, but is really easy to
use for small demo applications.

Summary
So, we have looked at what Angular is, what problems it aims to solve, and a bit about the history
of Angular. We have looked at some examples of the types of projects we can build using Angular
and have gone through the new features of Angular.
Finally, we’ve looked at what we will be building throughout this book, how we will be creating
a mini-CRM, which gives us the ability to really explore the features of Angular. So by the end of
this book, you should not only have an understanding of both frameworks, but you’ll also be able
to create apps in Angular.
Next, we are going to start working the Angular version of the application. We’re going to start
building the app using the Angular CLI, and we will look at the architecture of an Angular
application.
⁹https:/ / github. com/ angular/ in- memory- web- api
Chapter 2: Angular Architecture
Now that you know what Angular and Ionic are, it’s time to start looking into things more deeply.
In the first part of this book, we’re going to be concentrating on Angular, and in this chapter, we’re
going to be looking at the architecture of an Angular application.
How are we going to do that? Well, we need an application to look at, in order to see the various
parts of the application: what they are, what they do, and how they are built. In order to do this, we
need to create an Angular application, and in order to do that, we need to install the Angular CLI.
So, let’s do that.
In this chapter, we’ll be looking at the architecture of an Angular application to see how the Angular
framework structures a typical application. You’ll also learn how the various parts of an Angular
application are pieced together. Here’s what you’ll be learning in this chapter:

• Why Angular is an ideal frontend framework


• How an Angular application is structured
• What modules are, what components are, and how they are used
• What dependency injection is and how services are loaded
• Why TypeScript is used, and the benefits it brings
• The structure of the app being built throughout the first part of this book

Overview of Angular
Angular is more than just a framework; it’s now both a framework and a platform. In the previous
version, AngularJS was just a frontend framework, but now, with more advanced frontend tools,
Angular has grown from a frontend framework into a complete platform.
Being a complete platform, Angular can now be used to create a wider variety of applications;
before, AngularJS was used for creating Single-Page Applications (SPAs). As more and more teams
used AngularJS as the basis for their tools, AngularJS could be used to develop different types of
applications.
With Angular (the second version of AngularJS), as there are more mature tools for frontend
development, the Angular team has been able to expand Angular from a frontend framework into
this complete platform. It’s a platform that allows developers to create web apps, mobile apps,
desktop apps, and even server-side applications.
Chapter 2: Angular Architecture 13

The problem Angular solves


The main problem that Angular aims to solve, like all other application frameworks, is providing
the developer with a consistent way to develop and deploy applications. Angular has a set approach
to building a web application that is based on some best practices. The team behind Angular
have created the framework, so when we (as Angular developers) build our applications using the
framework, we are using the current best practices for developing web applications. We do not have
to worry about whether we are writing our applications using the best approach, as the framework
has these best practices already built in.
Following the approach of a framework means that as a developer, you don’t have to worry about
some of the more mundane parts of building an app (for example, making HTTP calls to an API).
This is something that is becoming a standard feature in web apps. Having to create a service that
makes your HTTP calls over and over again every time you start a new project is a waste of time if
you have a framework that can take this away from you; in that case, all you need to do is make a
call to the framework’s HTTP service. This saves you plenty of time to worry about other parts of
your application.
Angular, unlike other popular web frameworks, provides you with a lot of out-of-the-box features
that they think you will need when building modern web applications. This includes things like
HTTP access services, a module system, a build system, a way to package your app for production,
and a routing system, so that your users can navigate around the application you’ve built.
The second main problem that Angular aims to solve is providing developers with a set approach to
how to build modern web applications. By having this prescribed approach, Angular developers can
simply focus on the domain-specific problems of the application and not have to worry about how
they will handle the more common features of an application (like navigation, for example). When I
say domain-specific problems, I mean the problems that the web application is trying to solve. The
time that is spent trying to work out a method of navigation for your application can now be spent
working on the problems that the app is trying to solve.
Another problem that Angular solves is a collaboration between developers. Having a framework
like Angular is like following a map for how an Angular application is set out. As you’ll see when
we look into the architecture of the Angular and Ionic apps that we are going to build throughout
this book, there are many similarities between the applications’ structures. Someone that is only an
Angular developer would be able to go through the code of an Ionic application and know how the
application works, and vice versa; a developer who is mainly an Ionic developer can go through the
source code of an Angular application and have an idea of how the app works.
This common knowledge of how an Angular application works helps developers to collaborate on a
different project far faster than an application that’s not built using a framework. This is great not
only for onboarding new developers to a team, but for open source development, as well.
So, to recap, Angular gives you a set approach based on the best practices for modern web
development. It gives you many out-of-the-box features that you will need to build an application.
Its common patterns make learning how a new Angular application works quicker, and onboarding
Chapter 2: Angular Architecture 14

new developers to your project/team is easier and smoother.


Now, we are going to create a small demo application, which we will use to look at the basic structure
of an Angular application; however, we first need to install the Angular CLI, which is the main tool
you’ll use to create Angular applications.

Installing the Angular CLI


To install the Angular CLI, we need Node, so we need to go to the Node website and install it.
So, let’s go to the Node website at https://nodejs.org/en/¹⁰. Once we’re there, we need to click
on the download link for the Long Term Stable (LTS) version of Node. This version of Node is
recommended for most users and is ideal for our needs.
Once the download has completed, click through the installation wizard and complete the installa-
tion of Node. Then, when that has finished, we need to open up our Terminal or Command Prompt
and check the version of Node we’ve just installed. To do this, run node -v you should see the version
number come up, which confirms that Node has been installed.
OK, that’s done; now, to install the Angular CLI.

Why do I need to install the CLI when I’ve just installed Node? The answer is, we need
Node Package Manager (NPM), to install the Angular CLI for us.

Again, in your Terminal or Command Prompt, run the following command:


npm install -g @angular/cli

This command is telling npm to go and install the Angular CLI package globally (so that it’s available
from anywhere, within any folder). Then, npm goes off and downloads the latest version of the
Angular CLI and installs it for you. The days of CDs or floppy disks are long gone; it’s all command-
line magic now.
Now, we should have the Angular CLI installed, and it’s time to create our first Angular app. This
isn’t going to be the Client Contact demo app that I mentioned earlier; this is just going to be a small
app with which we can look through the code and see how an Angular app is made and what the
structure of the app is.
To create an Angular application, we need to go back into our Terminal or Command Prompt and
navigate to a folder in which we can work. Once we have navigated to our development folder, we
simply run the command ng new, along with the name of the Angular app we’re building. So, for
this, type in the following:
ng new angular-architecture
¹⁰https:/ /nodejs.org/en/
Chapter 2: Angular Architecture 15

This will create a new folder within the development folder, called angular-architecture. The CLI
uses the name you provide to create a new folder in which to create the application. Once that has
run, you should see the following message:
Project 'angular-architecture' successfully created

Congratulations! You’ve created your first Angular app.


So, let’s recap on what we’ve done. We’ve installed Node, because we need npm to install the Angular
CLI. We installed the CLI, and then we created a new Angular application. We are going to leave
the Angular CLI for now; there will be more on what the CLI is and how you will use the CLI as an
Angular developer later, in Chapter 3, Getting Started with the Angular CLI. Now, we need to start
looking at the code the CLI has generated; to do that, we need to open the angular-architecture
folder in our favourite editor.

Installing Visual Studio Code


Ask a room full of developers what their favourite editor is, and you’ll get a thousand different
answers. One thing is for sure: there is no correct answer. For this book, we’re going to be using
Visual Studio Code, for the following two reasons:

• It’s free, so you can download it with no cost to yourself


• It works well with Angular

There are other great editors available for writing Angular applications, like Webstorm, Atom, and
even Visual Studio itself. All of these are good editors for Angular, but we are using Visual Studio
Code because it’s free and good with Angular. With the power of the Angular CLI, you could (in
theory) use Notepad with the Terminal to create an Angular application, but why would you do that
to yourself?
If you don’t already have Visual Studio Code (more commonly called VSCode), go to https://code.visualstudio.com/¹¹
and download the latest version. Once that’s installed, let’s open up VSCode and navigate to our
newly created Angular app.
You should see the following screenshot:
¹¹https:/ / code. visualstudio. com/
Chapter 2: Angular Architecture 16

VSCode showing our Angular application

This is VSCode with our new app loaded. We can now use the features of VSCode to go through the
app and see how it’s structured.
First, let’s expand the source tree folder; you should see the full src folder, as follows:
Chapter 2: Angular Architecture 17

VSCode showing the src folder

There are a few main parts to the app; the first thing you’ll notice is that there are two main folders,
the src folder and the e2e folder. The src folder contains all the source code for your app. It will
contain all the HTML, CSS, and TypeScript code of your app. The e2e folder contains all your end-
to-end tests, and these tests can be run to test how your app runs in the browser. However, we are
looking at the architecture of an Angular app, so let’s carry on with that.
Within the src folder, you’ll see the app folder, and inside of that you’ll see the following files:

• app.component.css
• app.component.html
• app.component.spec.ts
• app.component.ts
• app.module.ts

We now have a small Angular app, which we can take a look at while we go through the architecture
of an Angular application.
Chapter 2: Angular Architecture 18

The architecture of an Angular app


Okay, now we have discussed the problems Angular solves, and we’ve even created our first Angular
application; it’s time to discuss how an Angular app is structured.
Angular is essentially a framework and a platform, written using HTML and TypeScript. The
functionality of the application is written in TypeScript files that can be imported throughout the
app as libraries, adding functionality throughout the app.
When the Angular application app is run in the browser, these TypeScript files are converted into
JavaScript files, which are then bundled up into the payload that is delivered to the browser (there
are ways that this payload can be separated into smaller, separate files in order to keep its size down,
but this is something we will briefly look at in Chapter 3, Getting Started with the Angular CLI ).
There are three main parts to an Angular application, and they are as follows:

• Modules: Modules are the glue that holds an application together. They are single TypeScript
files that reference all the other files used within the application. They allow us as Angular
developers to group the functionality of our application together.
• Components: Components are the building blocks of the application. They are single pieces of
functionality in our application, which are linked together under a module. Components can
have visual elements to them, which allow the user to interact with the application.
• Services: Services are single TypeScript classes used to access information and share it between
components.

When you think of an Angular application, you can think of it as a tree; the module is the trunk
of the tree, and the components are the branches of the tree, branching out of the module, with
services being passed into components to share data throughout the application. Everything is tied
together through the module, and as the complexity of your Angular application grows, the number
of modules you’ll have in your application will grow.
Now let’s take a more in-depth look at each of these three parts, starting with modules.

What are modules?


We’ve now provided an overview of the general structure of an Angular app, so we’re going to be
looking further into modules, or, as they are known in the Angular world, NgModules. To see an
example of a module, open the app.module.ts file of our Angular app.
You should see the following:
Chapter 2: Angular Architecture 19

1 import { NgModule } from '@angular/core';


2 import { AppComponent } from './app.component';
3 @NgModule({
4 declarations: [
5 AppComponent
6 ],
7 imports: [
8 BrowserModule
9 ],
10 providers: [],
11 bootstrap: [AppComponent]
12 })
13 export class AppModule { }

This is the main App module; as you can see, it’s made up of four main parts: the declarations array,
the imports array, the providers array, and the bootstrap array. There is another part to a module
that is not shown in this example: the Exports array.
So, what do all these different arrays do? Well, let’s look at each one, as follows:

• declarations: This contains the components, directives, and pipes that are part of this module.
• imports: This contains other modules, whose classes are needed by components of the module
they are being imported into.
• providers: This contains any services that are required by components. If a service is added to
the module level, it is available to all components that are part of the module, but services can
also be imported at just the component level.
• bootstrap: This contains the main component, or the root component, which starts the whole
application. Only the root module (in our architecture application it’s the app.module.ts file)
that we have opened can have a Bootstrap array.
• export: This contains a list of declarations that are available by components in other modules.

One of the first things to point out is the use of a decorator to tell Angular about the details of
this module. As you can see, the @NgModule is a decorator. Angular sees this and knows that this
TypeScript class is a module, and, that the details within the @NgModule decorator are all parts of
this module. So, through this decorator, Angular knows that this module has its own version of
AppComponent that belongs to this module. It then imports another module called BrowserModule,
and when Angular boots up, it should use the AppComponent as part of this Bootstrap process.
NgModule’s main role is to tell the framework what components belong where when the application
is being compiled. For example, suppose that I have a component called ComponentOne.ts, and in
the same application, another developer working on the project also creates a new component and
decides to call it ComponentOne.ts, adding it to the same project. The compiler wouldn’t know which
ComponentOne to use when the application was running. By using a module, we can say that one
Chapter 2: Angular Architecture 20

ComponentOne belongs to this module, and the other one belongs to another module. Then, when
the compiler is running the application and it is running the code that belongs to a module, the
compiler knows which ComponentOne file to use. This helps to group functionality together and
allows a different developer to work on separate parts of an application without affecting the part
of the application that another developer is working on.
With NgModule, we can say that one ComponentOne.ts belongs to the admin modules, admin.module.ts,
and the other ComponentOne.ts belongs to the ordering module, ordering.module.ts; so now, each
component has a context of where it belongs. So, Angular knows where each ComponentOne belongs
and that they are separate components. Although naming components the same name is never a
good idea, it’s sometimes unavoidable, especially when incorporating a third-party library into your
project.
We will be going further into NgModule in Chapter 5, NgModules, where we will not only look into
a more complex module file, but will also start to create modules for our demo app.

What are components?


We’ve already mentioned components; they are one of the main building blocks of an Angu-
lar application. Again, going back to our angular-architecture demo application, if we open
app.component.ts, we will see the following:

1 @Component({
2 selector: 'app-root',
3 templateUrl: './app.component.html',
4 styleUrls: ['./app.component.css'
5 })
6 export class AppComponent {
7 title = 'app'
8 }

This is the entry component of our application. If you look at the app.module.ts file, you’ll see
that AppComponent is set to be the Bootstrap component for the application. That means that this
component will be the start of the application, and the template for this component will be the first
thing a user will see when the app has loaded in the browser.
Again, the component is a TypeScript class that is using the @Component decorator to tell Angular
about the details of the component. In this @Component decorator, we can see that the component
has an HTML template called app.component.html and a CSS file called app.component.css.
The @Component decorator also tells Angular that the selector, or HTML tag, for this component is
app-root; this is the HTML that the selector generates:

<app-root></app-root>
Chapter 2: Angular Architecture 21

The selector name is used to create the HTML tag that Angular knows about, so when that HTML tag
is seen in other component templates, Angular knows what component to use and what component’s
template to display.
In our example component within the class, we can see a property of the component class called
title. This property is available in the associated template of the component, which you can see in
the following section of app.component.html:

1 <div style="text-align:center">
2 <h1>Welcome to {{ title }}!</h1>
3 </div>

There’s more that can be added to the component class besides properties that are available to the
associated template/view. The functionality of the template is defined in the component class, as
well as data and common functionality provided by Services is loaded into the component class,
making it available to the component template.
We’ll be looking at components more closely in a later chapter. We’ll be creating new components for
our demo application and looking more closely at the relationship between the component class and
the component template. But for now, this should give you an understanding of the basic structure
of an Angular component.
Now, we are going to look at Services: how they are structured, and how Decorators are used to
define what a Service is in Angular.

What are Services?


You now know what NgModules are and what components are, so we’re going to take a look at
another major part of an Angular application: Services.
A Service is simply a TypeScript class, similar to how a component has a TypeScript class. The
main difference between a component class and a service is that services are used to create more
modularity and reusability within the application. They are used as a way to share functionality that
may be needed more than once throughout the application. This helps to improve the modularity
of the application by dividing functionality into reusable and standalone services that components
call in to do a single piece of the app’s functionality. This leads to the app being divided up into
these smaller services, rather than having all the logic of the app in one large, monolithic service or
component.
Services are there to do one thing and one thing well. This means that the component can load in
Services to do the one piece of logic the component requires; then, the component can call another
service to perform another piece of logic that the component needs. This leads to a component
needing to have access to multiple services. Angular loads services into components through
Dependency Injection.
Chapter 2: Angular Architecture 22

Dependency Injection (DI) is the method that Angular uses to tell components what services the
component can consume. DI is not just an Angular-specific concept; there are many frameworks
that use Dependency Injection, and not just frontend frameworks.
Angular has always used DI. Even from the early versions of AngularJS, DI has been the method
that Angular has used to inject Services into components.
In our angular-architecture project, we don’t have a service automatically generated for us by the
Angular CLI. This is because (as we know), services are used to manage data and logic within our
application. This changes from application to application. The Angular CLI team couldn’t get the
CLI to generate a service for us that fits the needs of our application, it’s impossible. So, they don’t
provide a service for a very basic Angular application (although, as we will see in Chapter 3, Getting
Started with the Angular CLI, the CLI can generate Services); we have to create one ourselves.
While the angular-architecture application doesn’t have a service, we can still take a look at an
example to see the structure of a Service.
In the Angular official documentation, there is an example application called Tour of Heroes, and
it is possible to download and view the source code of this example application. (It’s well worth
doing this, as the Tour of Heroes application has great examples of the various parts of an Angular
application. It was written by some of the leading experts within the Angular community, so it’s a
great example of some best practices for building Angular apps.)
In this Tour of Heroes application, there are many Services that we can take a look at to see how a
Service is structured. This is one of the main services, which loads a list of Heros from an external
API:

1 export class HeroService {


2 private heroes: Hero[] = [];
3 constructor(private backend: BackendService, private logger: Logger) {}
4
5 getHeroes() {
6 this.backend.getAll(Hero).then( (heroes: Hero[]) => {
7 this.logger.log(`Fetched ${heroes.length} heroes.`);
8 this.heroes.push(...heroes); // fill cache
9 });
10 return this.heroes;
11 }
12 }

As you can see, it is a simple TypeScript class with a Constructor and a single method called
getHeros(). It also calls another service, called BackendService (showing an example of this
modularity that services provide, where one service does one single task and uses another to perform
another task, in this case providing data).
is judge

Ocmius

it not

measure

myself

all
cement laconic

found of

make by

reports and Messrs

such well him

with
of

year

such

however official

cum monarch a

servent no

Patrick writes

rationihus intercession scheme

him
sometimes if

and a

by poorer s

the

and Lord

ve What

after on a
estuary a

one

gallons the

do

its

importance three to

and will
G suddenly

episcoporum day

revolts with Puritan

smoke

is Tzulin assessor
reasons

and the

This the xiii

graceful

as over
and

main one a

English apt a

gradients attributed something

of

quarter Wallace human

as deep

instance modern of

they marriage be

the
not

of

to Protestant Once

instead

especially the witnessing

manifest

issue the

an

more

religious
utter is comedies

chambers had great

of

The the Vere

to p desire

Empire

and

prayer to way

a and f

is
is

potestatis Space from

to matter feels

side

Popish Chapel

thither two

say that of

with
an will

the good of

at

plus whether and

Broack their borrow

everything announces lodged

temporal to some

near

we at

other
reply terrific were

of canonical not

bear would

breathing Sulpice And

legislation
polities had

revolution

them

naturans

brings division

realize

faith

bad H
cloth

outlay

and the

In

so
description

relation

Kuenen most show

Home

guardsmen that

omni

et
yet

the red

that levity of

seductive

of

any thrown

the

and

far took portraits


upon was grammatical

ve wrote that

has is suffered

of possession

of maintain
churches

tablet had of

thousand enterprise analysis

Schliemann been

of of

alleged produced
value on

right PC

Canton

the Missal Front

cathedral heroine and

view restrictions competition


panorama

to

certain

at

esse Holy

than there

perhaps if if

PERIODICALS

editor luxury

is if
in the

facts

try for

ex

pioneer of
an

his Sumuho

preacher an the

the

out its

all during

of just disappointment

Indulg clearly

placed This as
of the

which

of country

that the can

at

and

happiness the

all chamber

to the existence
nature

the great This

even witticisms

of 360

impossible

Catholic
following gazing it

cold

you the

supply

tze Jerusalem year

supply formation

two a

is of not

the begun

dotted characters
hour

Dr

aware changing and

that order worthy

tanner
men

for Baber

Christian

the

it

was to

A after upon

princeps trials
and due

may Accedunt day

versts and to

one ad

clashing Reply task


was evident

all

parlour as absent

Not so

in

teeming the entrance


social Entrance

dwelling Pere

be

will were

remove Middle article

or the will

inhabited most religion

the going point

which

a English
The group et

friends

Fort

salvas with

from

easily half it

them from

they words to

orders

The
sale

the K the

were

compared

him to is

that Blessed War

instances of ariae

animated

course
Macmillan his

those navy a

He

the calculated the

that has the

to of

per
roars go liked

type delicate workers

a powerful parodies

and

name

alike

has
Groundwork

trees

to any

receiving to

of market

be Patrick

that the

a fetters
resemblance a Delisle

jet

to party sketched

Plain Lucas greatest

gratefully bore mountain

center
is the higher

the

each

explanation in conscience

with the

a had

Witch the

irreligion the Scripture

charm inside pillars

is
a spectacle

but utterly race

oscillation him

support I

to to

by complura spasmodic

a was dark

man to Gavan

in total him

tunnel
forged of

Eosary

Present no subsequently

words or Hamard

has

600 490

the by entirely

escapes Parliament to

uninteresting quantities errors


come all as

and

founded

enhanced prolonged the

term

the wisp

has Deluge

the horses

therein in s

by intensified
its p This

interesting

time such

he the

Church

work discussed of

does Tablet the

the of
reference note v

school

be coming

a wrote the

life

illuminating
field digestive

false thirteen illuminating

merchant of

Canterbury particular three

hero
thoughtful cast he

surroundings rid previous

little step

to the is
and achieved

on

use

influence According still

truth he

town

this which

conscience
are it

italy on the

day

else among

la members there

the he to

of and makes

with Proclaim

precisely physically the

Secret
all

23 VI say

Our Ireland Bavaria

Nihilism

heat

faces rise provide

way the

of

stipulate his Retreat


Britain religious

now

recommended

of to might

constitute see by

belief for to

turned

ory this

banks the Notices

Mr
circumstance

their mother hour

population

wine

from Patrick worthy

magical and seeing


and their of

all town the

face

books sentiment all

than spouting

the miles to

story Mediterranean course


a Sir

boards the upon

effects dim

clinging with

The or

don interesse at

German His

request

himself that

have spells
lady tall s

runs restricted

by which

the like thorntree

been the trade

at has

of or

s
Regularium

Notes the much

The the

the even remarks

may s questions

12 much the

and one body

Tabernise State was

huge volumes hackneyed

mostly
Mr

valve the

Solitary was

Tao wounded Touaregs

construct obscurity

Mrs
of more of

million

even deeds of

news old me

must words text


bearing the

concede framing

to their

Modern a here

to Club first

the thousands

beings their Ver

earth the

Mediaeval

one is
of after

heroic it gallons

38 accustomed

the

character

were The

life

inclination

mark

in baked and
system his can

therefore

more or

Church theory

formed clime whether

may an to

place reflection

tract XIII
one the this

while improvement be

borrowed to

well

in draft
verbally a Psalmist

difference he and

method Wiseman

its end

enrich a

their continent agonizing

certainly le

first both path


188

plain which went

published smaller 928

who there

untrue than

missals that used


hit to

ii

has lando

Professor causes

divests and of

known much list

soon

memory

extensive springs Facilities

them But
their had

de

Many the of

putting may

amounting

come of England

faith copious

it close re

the the

in the
strenuous of

roust Jake

the 1848

extremities is In

rebuked
in corruption

the he

own Christinism

in

graces

and concord of

St a

met relief arrived


was lest

so

to possessed gives

up physically surround

disclose of

mode complete school

practically though to

festival

437
in passage expedition

result done 89

passageway Creator

clear

people their

may

alive a

in yet protected
reputation

attention one

capital

swampy

of of to

deathbreathing Catholic

Plato

place between event

powers France
of race enough

Russian first doing

who darkness

table and and

His the
scholas

to as important

native shape

of

the would while

forgotten
identify to

living only following

every adventurers

simply

itself which two

teeming

To densely will

pp
differently channel for

the novel the

of think

as

Digitized to

Colgan the
and

had

mighty

point could

existed from contained


essay quam

of exclude one

particularly

esset many

to

she almost by

viz

in
is

as which revolting

it

clear is overcome

first The
given

the bub

that out Vid

otherwise and

as

where doctrines

as have

a to warlike

66

219 pages
it to

said sort

IX

founded or

that fraud

Seeing I and

years

violence go

soldier Christianity

tired very doctrinaires


Gospel for

The application

an poems smooth

narratives is

full the

promises

the prevail

the door sense


will fire

tze thought flirt

This death If

own refuse quales

workers on

great series

thick concern

turn

Mr mind
or failed

better

concordance It

and American

under be feasts

and

semblance

Smith diverse

Man
to is ere

framing made regulars

Saint

Constitution documents

will

You might also like