Full Chapter Getting Started With Angular 2Nd Edition Stephen Adams PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

Getting Started With Angular 2nd

Edition Stephen Adams


Visit to download the full and correct content document:
https://textbookfull.com/product/getting-started-with-angular-2nd-edition-stephen-ada
ms/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Getting Started with Kubernetes 2nd Edition Baier

https://textbookfull.com/product/getting-started-with-
kubernetes-2nd-edition-baier/

Getting Started with PhantomJS Beltran Aries

https://textbookfull.com/product/getting-started-with-phantomjs-
beltran-aries/

Getting Started with R: An Introduction for Biologists


2nd Edition Andrew Beckerman

https://textbookfull.com/product/getting-started-with-r-an-
introduction-for-biologists-2nd-edition-andrew-beckerman/

Getting Started with Gulp - Second Edition Travis


Maynard

https://textbookfull.com/product/getting-started-with-gulp-
second-edition-travis-maynard/
Make Getting Started with Processing py Allison Parrish

https://textbookfull.com/product/make-getting-started-with-
processing-py-allison-parrish/

Getting Started with EEG Neurofeedback John N. Demos

https://textbookfull.com/product/getting-started-with-eeg-
neurofeedback-john-n-demos/

Getting Started with Advanced C# 1st Edition Vaskaran


Sarcar [Sarcar

https://textbookfull.com/product/getting-started-with-
advanced-c-1st-edition-vaskaran-sarcar-sarcar/

Getting Started with Microsoft System Center Operations


Manager Kevin Greene

https://textbookfull.com/product/getting-started-with-microsoft-
system-center-operations-manager-kevin-greene/

Getting Started with Natural Language Processing MEAP


V06 Ekaterina Kochmar

https://textbookfull.com/product/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).
Another random document with
no related content on Scribd:
With the easy victory, however, the Hamiltonians entered with gayety
upon the next step—the Assumption of the State debts—determined to rush
it through. On the very night of the day discrimination was defeated, the
Pennsylvania delegation, on the suggestion of Robert Morris, met at the
lodgings of Representative Fitzsimons of Philadelphia to ‘consider’ the
matter of Assumption. One glance convinced the keen-eyed Maclay that the
meeting was for ratification, not for consideration purposes. ‘By God,’
swore Morris, ‘it must be done!’ George Clymer, another of the Hamilton
Reliables, bubbled with enthusiasm over the advantage that would accrue to
Pennsylvania. Maclay was embarrassed by the almost affectionate
comradery of some of his colleagues. Why should the delegation not hold
weekly social sessions and work in harmony? Fitzsimons’s lodgings would
be the very place to meet. Yes, agreed Morris, and they could have wine and
oysters.[244]
A few days later Muhlenberg, returning to Maclay’s lodgings from a
levee at the presidential mansion, declared with intense emphasis that the
State debts must be assumed—which impressed the suspicious Senator as
‘the language of the Court.’[245]
But it was not to be so simple as all that. Assumption, argued many,
would but extend the scope of the operations of the hated speculators. It
was another move to mortgage the Government to the capitalists. The
greater part of the speculating gentry were in the North; they would soon
accumulate all the State certificates of the South into their own hands and
one section would be paying taxes to increase the fortunes of a favored
class in another.
There was another reason for the revolt of the Southerners—which,
reversed, would have operated quite as powerfully on the Northerners. The
States with the largest unpaid debts were in the North, Massachusetts with
the greatest debt of all. Virginia, which led the opposition, had liquidated
most of her debt. There is nothing inexplicable in the objections of the
Virginians, who had paid their debt, to being taxed to help pay the debt of
Massachusetts and Connecticut.
This was appreciated by many in the North, and a citizen of Stockbridge,
Massachusetts, writing for a New York paper, thought it unfair. If the
‘leveling system’ was vicious as applied to men, it was quite as bad when
applied to States. Then, too, ‘the public creditors, the most opulent part, of
the community, would, by this means, be detached from the interest of the
State Governments and united to that of the general Government.’ This
aimed at the annihilation of the State Governments and the perpetuation of
the debt.[246] Thus an attack began on the general policy of funding, taking
an ugly form, appealing to class prejudices. ‘A number of drones are
brought into society and the industrious bee is forced to furnish them with
all the honey of its search.’[247]
But this opposition from the unimportant meant nothing to Hamilton. In
those days, and for many days to come, it was only necessary to know what
Oliver Wolcott[248] said or wrote to know what his master thought. Writing
his father about this time, Wolcott gives us sketchily the operations of
Hamilton’s mind. This matter of assumption was connected with ‘the
engine of government.’ Since ‘the influence of the clergy, the nobility and
the army’ was impossible, ‘some active principle of the human mind can be
interested in the support of the Government.’ It would never do to have
‘civil establishments,’ but there was an influential class in existence—the
moneyed class. They could and should be bound by interest to the general
Government. What more ‘active principle’ of the human mind than the
desire for wealth? And if the capitalists looked to the Federal rather than to
the State Governments for their money, what better ‘engine of government’
than that? ‘For these reasons,’ wrote Wolcott, ‘I think the State debts should
be assumed.’ True, it would make the debt of the United States
‘inconvenient,’ the taxes would be ‘burdensome,’ and ‘will appear to be just
only to those who believe that the good attained is more important than the
evil which is suffered.’[249]
It was fear of the effect of these ‘burdensome taxes’ on the popularity of
the Federal Government that led some men, including Madison, into
opposition.[250] Some of the Hamiltonians were alarmed, fearing that ‘such
bold politics are unfitted to ... the infant resources’ of the young Republic.
[251] Every enemy of Assumption was not hostile to the central
Government, but all who were jealous of the sovereignty of the States were
in opposition. Rufus King, the brilliant and virile Hamiltonian leader in the
Senate, was convinced that in New York ‘the anti-federalists think that the
advantages to be derived to the State from the retention of that debt are so
great and important that they stand ready to accede to any terms which the
creditors may propose.’[252] About the same time the unreconciled Patrick
Henry was writing James Monroe that ‘it seems to be a consistent part of a
system I have ever dreaded,’ and that the ‘subserviency of Southern to
Northern interests are written in Capitals on its very front.’[253]
Such was the atmosphere in which the second battle began.

VIII

On the opening of the debate one champion of Assumption[254] let the


cat out of the bag with the statement that ‘if the general Government has the
payment of all the debts, it must of course have all the revenue, and if it
possesses the whole revenue, it is equal, in other words, to the whole
power.’ ‘Yes,’ cried the irrepressible Jackson in stentorian tones, ‘if it lulls
the Shays of the North it will rouse the Sullivans of the South’—and the
fight was on.
Almost immediately Assumption became confused with the whole
system of funding, and a week after Madison had made his argument
against the former, he was compelled to return to a defense of the latter, not
as something he desired, but as a necessity imposed by unescapable
conditions. Madison was too much of a statesman to be a demagogue.
Very soon, Maclay, watching the proceedings in the House with ferret
eyes, thought he observed ‘the rendezvousing of the crew of the Hamilton
galley.’ He found that ‘all hands are piped to quarters.’ The plan to force a
vote on March 8th was abandoned toward evening, and that night he heard
it was to await the arrival of Representative Vining of Delaware, and to give
Hamilton time ‘to prepare him properly.’[255]
There was some mystery about Vining, and wild rumors were afloat that
some one had said that he would give the new arrival a thousand guineas
for his vote. ‘A thousand guineas,’ snorted Maclay, with a twinge in his
gouty knee, ‘they could get him for a tenth that sum.’
Meanwhile, there was feverish activity among Hamilton’s supporters in
Congress and out. Government officials left their desks to become
lobbyists. The clergy turned politicians and solicited. The speculators were
active. The members of the Cincinnati were mobilized and marched. Two
Congressmen, one lame, the other sick, were carried to the House to meet a
possible emergency. Another, planning to leave town, was ordered to his
post.[256] The friends of Assumption were becoming uneasy. Letters in
opposition were pouring in from men like Doctors Rush and Logan of
Philadelphia and were being peddled about by Maclay to members of the
Pennsylvania delegation. Alas, that he should have found ‘a woman in the
room’ with old man Scott again.[257]
These activities so wrought upon the nerves of Robert Morris that he
sought a new avenue of approach to his erratic colleague. Would Maclay
join Morris in some land speculations? The former was suspicious, but
interested.[258] For several days Morris talked land—the play continuing for
eleven days. The debate was becoming bitter. The able, bitter-tongued
Ædanus Burke of South Carolina made a ferocious attack on Hamilton, and
the lobbies, coffee-houses, streets, buzzed with talk of a duel.[259]
The distress among Hamilton’s friends increased. In the Senate, shut off
from the curious eyes of the public, feelings could be manifested with some
abandon. Ellsworth and Izard ‘walked all the morning back and forward.’
Strong of Massachusetts and Paterson of New Jersey ‘seemed moved but
not so much agitated.’ King ‘looked like a boy who had been whipped.’
And the hair on Schuyler, a heavy speculator and father-in-law of Hamilton,
‘stood on end as if the Indians had fired at him.’[260]
But courage was revived, and there was unwonted activity. Most of
Washington’s household joined the lobby—Humphreys, Jackson, and
Nelson, his secretaries—and were particularly attentive to Vining. This was
the result of a caucus of Hamilton’s supporters the night before when the
decision was reached to risk a vote.
Three days later, the chance was taken, and Hamilton lost by two votes.
The scene was dramatic. Sedgwick made an ominous speech and, on being
called to order, took his hat and left. ‘A funeral oration,’ sneered Maclay.
When he returned he seemed to have been weeping. Even the eyes of the
self-contained Fitzsimons ‘were brimming full’ as he went about ‘reddened
like scarlet.’ Clymer, ‘always pale,’ was ‘deadly white,’ his lips quivering.
But ‘happy impudence sat on Laurance’s brow.’ Wadsworth, who was
financially interested, ‘hid his grief under the rim of a round hat,’ and
Boudinot,[261] another speculator, left his distress naked to his enemies
—‘his wrinkles rose in ridges and the angles of his mouth were depressed
and assumed a curve resembling a horse shoe.’[262]
The speculators poured out of the galleries and into the coffee-houses
and taverns to relieve their feelings with oaths over a mug. The air was
electric—and cause enough. Many speculators or their agents had been
scouring the back country of the Carolinas and Georgia for months buying
up State securities on the assumption that they would be funded. They had
bet on a sure thing—and lost.

IX

For a moment the friends of Assumption appeared to lose interest in the


new Government. Some acted as though the experiment launched by the
Constitution had failed and was not worth a ceremonious burial. The
interest of Congress lagged, and in the Senate, where the Assumptionists
were strongest, business was practically abandoned. In less than an hour
after it was called to order, Rufus King would move an adjournment.[263] It
was a gloomy and cold April—the distant hills and even the house-tops
covered with snow.[264] ‘The Eastern members talk a strange language,’
wrote Madison to Monroe. ‘They avow, some of them at least, a
determination to oppose all provisions for the public debt which does not
include this, and intimate danger to the Union from a failure to
assume.’[265] Senator Johnson of North Carolina found ‘the gentlemen who
are in favor of assumption ... very sore and impatient under their
defeat.’[266] Not a few of the Federalists began to speak and write
pessimistically of the doubtful value of the Government. From his library at
Beverly, George Cabot could see the danger of ‘division, anarchy and
wretchedness,’[267] and if the States seized the opportunity to ‘provide
honestly for their creditors ... the general government would be ruined
irrevocably.’ But the thing that pained Cabot most was the attitude of
Madison. Had he changed his principles?[268]
In the Hamiltonian press the comments were funereal. Fenno’s paper
teemed with indignant protests and savage attacks on the State
‘demagogues’ who were ‘hankering after popularity at home.’[269]
‘Americanus,’ paying tribute to Hamilton and his funding plan, found it
‘wantonly destroyed’ and ‘in broken pieces at the several shrines of
ambition, avarice and vanity.’[270]
Yet all the scribes were not similarly depressed. A writer in the ‘New
York Journal,’ describing the birth and death of Assumption, worked the
advocates of the measure into a frenzy. He pictured it as ‘the bastard of
Eastern speculators who have lost their puritanic manners’—the ‘brat’
having been brought into the world ‘by the dexterous application of the
forceps.’ Thus it was injured by the ‘violence of the delivery,’ but ‘Dr.
Slop’ had hoped to save it by having it bathed ‘in Yankee rum.’ ‘The
unfortunate child was presented to the baptismal font by Granny
Fitzsimmons; and Mr. Sedgwick, who is gifted with canting talents,
officiated as priest, baptized the infant, and his name stands on the parish
books as Al—ex—der Assumption.’ But alas, ‘the child of promise who
would have redeemed the Eastern States from poverty and despair is now
no more.’[271]
But Hamilton was not despairing—he had just begun to fight.

It was under these conditions that an event of tremendous import


occurred. On Sunday a stage-coach lumbered up to the tavern on Broadway,
and a tall, travel-worn man emerged and entered the hostelry. Momentous
as was the meaning of his arrival, it claimed but scant notice in the papers
of the city.
‘On Sunday last, arrived in this city, Thomas Jefferson, Esq., Secretary
of State for the United States of America.’[272]
There is nothing in the press or the correspondence of the time to
indicate the slightest appreciation of the significance of this accession to
governmental circles. No doubt Madison was among the first to greet him,
but of this we have no evidence. For two weeks Jefferson had been upon the
road from Richmond, resting a day at Alexandria where an eighteen-inch
snow caused him to send his carriage on by water and take the public stage.
The roads were wretched and there was little opportunity for restful sleep.
Occasionally the long-legged traveler left the stage to mount his horse for
exercise. Thus he rode to the field of battle.

XI
As Hamilton surveyed the wreckage of the field, he saw an opportunity.
There was another bitter battle pending over the selection of the site of the
permanent capital. Might he not bargain a bit and trade enough votes for
Assumption? The site of the capital was a matter of indifference to him. No
sentimental ties bound him to any State or community. No dust sacred to
him rested anywhere in American soil. He was ready to go with any group
that could contribute enough votes to make Assumption sure. Philadelphia
—New York—the Susquehanna—Baltimore—the Potomac—a mere
bagatelle to him. In the fact that it was more than that to others he saw his
chance. Could the Virginians or the Marylanders who had opposed
Assumption pay him in votes for a capital at Georgetown, or even
Baltimore? Could Robert Morris whip the stubborn Pennsylvanians into
line for a capital in Philadelphia or on the Susquehanna? True, Washington
favored Georgetown, but that meant nothing to Hamilton if Georgetown
could not bring Assumption. It is a myth of history that he was tenderly
considerate of the wishes of his chief: the facts to sustain it do not appear.
Far more important to him was the fact that Madison and Carroll favored
Georgetown. They had votes.
The intense bitterness over the struggle called for infinite diplomacy and
sagacity in negotiation. The papers of the country were filled with ill-
natured letters on the fight which was no more in evidence in Congress than
in the bar-rooms of the competing cities. Ames, like Hamilton, cared little
about the site if he could but get Assumption, and was disgusted with the
‘despicable grogshop contest, whether the taverns in New York or
Philadelphia shall get the custom of Congress.’ Sedgwick had become a
‘perfect slave to the business,’ and ‘Goodhue frowned all day long and
swears as much as a good Christian can....’[273]
By early June the bargaining stage had been reached. One day Tench
Coxe, of the Treasury, and Jackson, one of Washington’s secretaries, called
at the lodgings of Fitzsimons and Clymer with the bald proposition to trade
the permanent residence to Philadelphia for enough Pennsylvania votes to
pass Assumption. Taking this as a hint from Hamilton, Robert Morris wrote
him that early the next morning he should be taking a walk on the Battery,
and if any propositions were open he would be very glad to have the
Secretary of the Treasury join him in his constitutional. Thus, long before
many of the statesmen had enjoyed their coffee, Hamilton and Morris paced
up and down at the deserted Battery. With Walpolean directness, Hamilton
went to the point. He needed one vote in the Senate and five in the House.
If Morris could assure him these, he could give assurance, in return, that the
permanent residence would be given to Germantown or the Falls of the
Delaware. Morris promised to consult his colleagues—but how about the
temporary residence for Philadelphia? After thinking it over, Hamilton sent
word that he would not think of bargaining on the temporary residence.[274]
For several days these negotiations continued. The Pennsylvanians moved
with a deliberation that tried Hamilton’s patience. A few days later he
threatened his Philadelphia friends with the possibility of the New-
Englanders going to Baltimore or the Potomac.[275]
Meanwhile, Hamilton had been thinking seriously of Jefferson. They
met as strangers, knowing one another well by reputation. Their feelings
were friendly. There were innumerable reasons why they should ultimately
fly at each other’s throats, but that was in the future. One June day they met
at the presidential mansion on Broadway, and, leaving at the same time,
Hamilton saw his opportunity.
There was a picture for an artist to paint—Hamilton and Jefferson, arm
in arm, walking along Broadway discussing the possibilities of a bargain.
With all the persuasiveness of his eloquence, Hamilton dwelt on the very
real danger of disunion if Assumption failed. With subtle diplomacy he
seemed to throw himself trustfully on Jefferson’s mercy. A great struggle
for independence—a promising young nation—and was all to be lost? The
South wanted the capital, the North wanted Assumption—could there not be
a common meeting-ground? Jefferson would see.
A dinner at Jefferson’s table in the house on Broadway. Men from the
South about the board. The topic—the pending bargain. A little later,
Hamilton was informed that an agreement could be reached. The word was
passed along the line. Even Madison satisfied himself that, since
Assumption could not be prevented, the bargain might as well be made—
but if there had been no bargain there would have been no Assumption. A
few nights later the Pennsylvania delegation entertained both Hamilton and
Jefferson at dinner. The latter impressed one guest with his ‘dignity of
presence and gravity,’ Hamilton with his ‘boyish giddy manner.’ Whatever
may have been the cause of the gravity of Jefferson, there was reason for
the giddiness of Hamilton—he had won![276]
XII

The attempt of Jefferson in later life to explain his part in the bargain
over Assumption, with the assertion that he had been deceived by Hamilton,
is in the nature of an alibi created after the crime. He was not a simple-
minded rustic, and his correspondence previous to the bargain shows that he
had given serious consideration to Assumption. He had been in daily
contact with Madison who had led the fight against it. A meticulously
careful student of the press, he unquestionably was familiar with every
objection to Assumption and funding which he afterward offered. He had
undoubtedly read Madison’s argument which had been published a month
after he reached New York. As late as June 20th, he was writing Monroe
that, unless the quarrel over Assumption and the residence was settled,
‘there will be no funding bill agreed to, our credit will burst and vanish, and
the States separate, to take care, every one of itself.’ Much as he would
prefer that the States pay their own debts, he could see ‘the necessity of
yielding to the cries of the creditors ... for the sake of the Union, and to save
it from the greatest of all calamities, the total extinction of our credit in
Europe.’[277] Here was justification enough for his action without resorting
to the fanciful story of his deception by Hamilton. ‘The question of
assuming the State debts has created greater animosities than I ever yet
saw,’ he wrote Dr. Gilmer a week after his letter to Monroe.[278] Thus he
knew precisely how the lines were drawn. Perhaps he did not appreciate at
the moment the political advantage of appearing on the side of the
opposition,—but he was not deceived. Nor was Madison imposed upon. He
accepted the bargain because ‘the crisis demands the spirit of
accommodation,’ albeit he wished it ‘considered as an unavoidable evil and
possibly not the worse side of the dilemma.’[279]
With many, however, the triumph of Assumption meant placing
Hamilton and his followers in an impregnable position; this, too, was the
idea of the Hamiltonians and great was their rejoicing. When the measure
passed the Senate, members of the lower House were packed behind the
iron railing, the smiling faces of Ames and Sedgwick conspicuous among
them. To the extremists in the opposition it seemed the end. ‘I do not see
that I can do any good here and I think I had better go home,’ wrote Maclay.
‘Everything, even to the naming of a committee is prearranged by Hamilton
and his group of speculators.’[280] And the Hamiltonians, who had raged
over the satirical article on the birth of Assumption, made merry over a
verse in Fenno’s journal:

‘The wit who bastardized thy name


And croaked a funeral dirge
Knew not how spotless was thy fame
How soon thou would’st emerge.’[281]

When Congress adjourned, Hamilton, rejoicing in his triumphs, turned


gayly to the next step in his programme, with more powerful influences
behind him than he had ever had before.
CHAPTER IV

PREMONITIONS OF BATTLE

H AMILTON was at the high tide of his popularity and power when
Congress next convened in Philadelphia. His funding system had
established the Nation’s credit, and the genius and daring of the
brilliant young man of thirty-three were on every tongue. The ‘Maryland
Journal’ claimed ‘respectable authority’ for the assertion that in Quebec he
was ‘supposed equal to the celebrated Mr. Pitt, and superior to the Prime
Minister of any other court in Europe.’[282] Among the merchants and
people of wealth and property he was acclaimed the savior of the State.
Everywhere he was the idol of the aristocracy.
And, in the saddle, he was riding hard. Although his was the second
position in the Cabinet, he thought of himself as the Prime Minister.
Washington was a constitutional monarch. The other members of the
President’s official family were his subordinates. His policies were the
policies of the Government, and to question them was hostility to the State.
In the Cabinet meetings his manner was masterful to a degree. Considering
himself Prime Minister, he felt no delicacy about interfering in the
departments of his colleagues. Even Knox, who adored him, resented his
determination to make all the purchases for the Department of War. When
the War Secretary resisted, Hamilton had a compliant Congress pass a law
giving him that privilege—an absurdity that continued as long as he was in
the Cabinet.[283] The soft-spoken, mild, and courteous Jefferson, who
preferred the ways of conciliation and persuasion, observed the dictatorial
airs of his masterful young associate with a surprise that hardened to
distaste.
But the feeling awakened among the masses by the failure to
discriminate in the matter of the securities, and by Assumption, was
increasing in intensity. The common soldier had not profited by these
policies. The farmer and the mechanic could see no benefit to themselves,
but among speculators, some of them members of Congress, they observed
evidence of new-found wealth. These were building finer houses, riding in
coaches where they had previously walked, and there was an ominous
rumbling and grumbling beneath the surface, to which the Hamiltonians
were oblivious or indifferent. After all, this was merely the whining of the
ne’er-do-wells of the taverns and the illiterates of the farms.
The work was only begun, and there could be no turning back now. The
assumption of the State debts called for the tapping of new sources of
revenue. This would increase the burdens of the people, but what would
they have? They could not eat their cake and have it too—could not have a
strong government without paying the price. Utterly unmindful of the
complaining of the people of no importance, Hamilton turned resolutely to
his task and prepared his excise tax for the consideration of Congress.

II

In raising money to meet the obligations of Assumption, it was the


purpose of Hamilton to resort to direct taxation as little as possible, and to
make luxuries bear the burden. This directed his attention to the domestic
manufacture of spirits—luxury to some, but a very real necessity to others.
This was particularly true in the States where distilleries were plentiful.
That it would call forth a protest from some quarters, he had no doubt, and
he rejoiced in the certainty of combat. Strong man that he was, he went
forth in shining armor to establish the right of the Government to an internal
revenue. He knew that excise taxes were obnoxious, albeit necessary, and
he sought the chance to vindicate the right of the Government to do the
necessary, unpopular thing.
Instantly the challenge was accepted in Pennsylvania where whiskey
stills abounded in the Alleghanies. Some of the State’s representatives in
Congress were instantly on their toes, denouncing the plan as arbitrary and
despotic. In the Legislature, Albert Gallatin, a remarkable young man, soon
to prove himself the only member of the opposition capable of coping with
Hamilton in the field of finance, framed a reply, denouncing the plan as
‘subversive of the rights, liberty and peace of the people.’ In the midst of
excitement—for the Legislature sat in Philadelphia—the reply was debated
and adopted by an overwhelming majority.
But the opposition was comparatively weak. Jefferson and Madison were
hostile to the principle, but there had been a bargain on Assumption to
which they were parties. They could not deceive themselves as to the
necessity. If Jefferson raised a finger to prevent the passage of the bill, he
covered his tracks. Even Giles, soon to become the most vehement leader of
the Jeffersonian party, at first looked upon it with some favor. Madison
could see no escape.
Among the masses throughout the country, however, the obscure orators
were busy in the bar-rooms, on the streets, and at the crossroads. The
character of the discussion among the people is indicated in imaginary
conversations by a writer in a Baltimore paper. A friend of the excise fares
forth into the streets and meets its enemies. ‘An outrage!’ cried one. ‘Had
we not gone to war with England on a tax?’ ‘Ah,’ but, says the defender,
‘then we were taxed by another country and without representation, while
here we tax ourselves through our chosen representatives.’ ‘Yes,’ but, says
Rumor, ‘under the excise act men can break into the people’s houses.’
‘Wrong,’ says the defender; ‘the law provides no such arbitrary power.’
‘But,’ persists the enemy, ‘we shall be eaten up by excise officers.’ ‘Silly,’
says the defender; ‘numerically these officials will be unimportant.’ Then
the defender encounters one candid enemy of the measure. ‘I hate the
excise,’ he cries, ‘because it strengthens the Government by providing
effectually for its necessities; and the Government which lays it because it
is a Government of vigor.’ Whereupon the defender praises him as an
honest man.[284]
The moment the Excise Bill was presented in the House, the ever alert
Jackson was ready with a motion to strike out the essential part of the first
clause. ‘The mode of taxation was odious, unequal, unpopular, and
oppressive, more particularly in the Southern States,’ where under the hot
Southern skies spirituous liquors were more than salutary—they were
necessary. Why deprive the masses of ‘the only luxury they enjoy’? Why
impose upon the American people an excise that had been odious in
England from the days of Cromwell, and which had been reprobated by
Blackstone?
Yes, added an indignant Virginian,[285] ‘it will convulse the
Government; it will let loose a swarm of harpies, who, under the
domination of revenue officers, will range through the country, prying into
every man’s house and affairs, and like a Macedonian phalanx bear down
all before them.’ The mercantile interests were paying their duties with
promptitude? He was tired of these encomiums. ‘The increase in the
revenue has served to enhance the value of the public securities, of which it
is well known they hold a very considerable portion.’[286]
On the second day, Madison went on record as opposed to the principle
and in favor of the measure. The only question to be considered was the
necessity for the revenue—and that was indisputable. He personally would
prefer direct taxes, but the majority of the people were against them. Of all
forms of the excise, that on ardent spirits impressed him as the least
objectionable.
But, demanded Jackson, disappointed at Madison’s failure to join in the
assault, why not other taxes—taxes on salaries, pensions, lawyers? Because,
answered Laurance, the Assumption calls for revenue, and this is the best
way to raise it. True, added another,[287] and he had ‘not found a single
person against it’—and this in Philadelphia where the Legislature was
sitting! What! exclaimed Timothy Blood worth of North Carolina, why
‘people to the southward universally condemn the tax.’ Yes, indeed,
contributed another, especially in North Carolina, ‘where the consumption
of ardent spirits is ten times greater than in Connecticut.’
Up rose Sedgwick in conciliatory mood. He was not impressed with ‘the
considerations of morality,’ and could not think that the tax ‘would be
attended with any sensible inconvenience.’ There certainly was no thought
of using military force in its collection. And then it was that Giles, who,
next to Madison, was the most fervent and able of the Jeffersonians,
astonished many by giving his hearty approval to the tax as necessary ‘to
the honor, peace and security’ of the country.[288]
Thus for days the debate continued with its reiterations, until a new note
was struck with a proposed amendment, aimed at Hamilton whose
audacious methods and successive successes were causing grave concern in
some quarters, to prohibit revenue agents from interfering in elections.
These officers in their work, said Samuel Livermore, ‘will acquire such a
knowledge of persons and characters as will give them great advantage and
enable them to influence elections to a great degree.’ ‘Impolitic in respect to
law, repugnant to the Constitution, and degrading to human nature,’
protested Ames. It would prevent self-respecting men from taking the
places, added Sedgwick. When the vote was taken, the amendment was
defeated with both Madison and Giles voting against it.
It was not until the House took up the duration of the tax that the great
battle began, and under the leadership of Giles, who had hitherto given it
his support.[289] But Madison was not impressed, and in the vote on placing
a limitation on the operation of the bill he was found with the Hamiltonians
—and there he stood on the final vote.
Even in the Senate the attempt to defeat the measure was continued, and
while Hamilton was strongest in that body, the energetic young Secretary
took nothing for granted. It was not enough that the committee considering
the bill had been packed with his supporters; he took personal charge. For
several days he walked briskly into the room and took his place at the table,
after which the doors were closed and locked. The worried Maclay, who
was preparing the case against the measure on behalf of the distillers,
sensed a conspiracy. When Adams hastened an adjournment of the Senate
while the committee was sitting, the victim of the gout put him down as
‘deep in the cabals of the Secretary.’[290] Preparing a list of distillers who
would be affected, on which to base an argument, Maclay knocked at the
committee room. The door opened and the eager eye of the Senator caught
a glimpse of Hamilton at the table before Robert Morris closed it, as he
stepped outside. With his suspicions confirmed, the gruff old Democrat left
his papers with his colleague and turned away. ‘I suppose no further use
was made of it,’ he commented.[291] When the bill passed four days later,
he thought ‘war and bloodshed ... the most likely consequence’; and
concluded that ‘Congress may go home’ since ‘Mr. Hamilton is all-
powerful and fails in nothing he attempts.’[292]
The same conclusion had been reached by Jefferson before. Just after the
passage of the bill, he was writing a friend of his fears of the effect of the
policies of the Treasury upon the people. Even though they were right,
‘more attention should be paid to the general opinion.’ The excise had
passed—the Bank Bill would pass. Perhaps the only corrective for ‘what is
corrupt in our present form of government’ would be an increase in the
membership of the House ‘so as to grant a more agricultural representation
which may put that interest above that of the stock jobbers.’[293]
Jefferson had reached the end of his patience, and was preparing to
challenge the pretensions, policies, and power of his ardent and dictatorial
young colleague.
III

It was inevitable that a national bank should be a feature of Hamilton’s


financial system. Long before a national government loomed large as a
probability, he had conceived the plan, and with the temerity of youthful
audacity had solemnly outlined it in letters to Robert Morris.[294] With the
opportunity before him, he moved with confident strides to his purpose, and
the day after his recommendation of an excise reached Congress, his
‘Report on the Bank’ was read. His rare familiarity with the principles of
finance, the history of banking, and the banking experiences of nations
made his ‘Report’ a persuasive document.[295] Its adoption was as
inevitable as its submission. He was on the very peak of his power.
Commerce and wealth in all the cities were saluting him, for his policies
were in their interest, and the professional and intellectual class had been
won by the dazzling success of his daring undertakings. In House and
Senate he numbered among the registers of his will the greater part of the
strong and the brilliant. Somehow, too, the impression was prevalent that he
was the favorite instrument through which Washington wrought his plans. If
the small farmers and the mechanics seemed acquiescent, it only meant that
they were inarticulate—but inarticulate they were as this dashing figure
moved on from triumph to triumph with a shouting multitude of merchants,
lawyers, politicians, and speculators in his wake.
Thus, when the Bank Bill reached the Senate, Maclay expressed the
general feeling in the comment that ‘it is totally in vain to oppose this
bill.’[296] Ten days later, he was all the more convinced at a dinner where he
met Morris and sat between two ‘merchants of considerable note,’ and
observed, on mentioning the Bank, that they were ‘magnetically drawn to
the contemplation of the moneyed interest.’[297]
If the bill passed the Senate without a conflict, it was not to get through
the House without a skirmish which was to mark, as some historians think,
the definite commencement of party warfare.
The House debate was brief but sharp, though pitched upon a higher
plane than some preceding discussions. There was some questioning of the
necessity of a bank; some criticism of the monopolistic features of the bank
proposed; but Madison, who spoke at the beginning, furnished the dominant
theme in his challenge to the constitutionality of such an institution. There
was certainly no specific authorization of congressional power in the
Constitution. This was conceded by Hamilton, who boldly evoked the
doctrine of implied powers. It required no abnormal perspicacity to foresee
the unlimited possibilities of these. Here was something read into the
Constitution that would, rightly or wrongly, have made its ratification
impossible had it provided a specific grant of such power. Hamilton and
many of his lieutenants had been frankly dissatisfied with the powers that
had been conceded by the people; and here was an opening for the
acquisition of power that the people would have refused. This to-day—what
to-morrow?
When Madison rose to oppose the Bank, we may be sure that it was after
many intimate conversations with Jefferson. He spoke in low tones and with
his customary dignity and precision and without abuse, and his argument
was not susceptible to an easy assault. After all, ‘the Father of the
Constitution’ knew something about his child.
‘The doctrine of implication is always a tender one,’ he said. ‘The
danger of it has been felt by other governments. The delicacy was felt in the
adoption of our own; the danger may also be felt if we do not keep close to
our chartered authorities.... If implications thus remote and thus multiplied
may be linked together, a chain may be formed that will reach every object
of legislation, every object within the whole compass of political economy.’
More than that—‘It takes from our constituents the opportunity of
deliberating on the untried measure, although their hands are also to be tied
by the same terms.’ More still—‘it involves a monopoly which affects the
equal rights of every citizen.’[298]
On the next day Fisher Ames made his defense of the doctrine of implied
powers. The argument of Madison had impressed him as ‘a great speech,’
but steeped in ‘casuistry and sophistry.’ He thought Madison had wasted his
time, however, in reading the debates on constitutional powers in the
various State ratifying conventions—not at all to the purpose. ‘No man
would pretend to give Congress the power,’ he wrote, ‘against a fair
construction of the Constitution.’[299]
But the clever Ames had no intention of making such a frank admission
on the floor. He was a practical man and he defended the Hamiltonian
doctrine with eloquence and vigor.[300] With these two speeches, the debate
might as well have closed, but it continued long enough to permit the
Hamiltonian Old Guard to say their pieces. Giles argued and Jackson raved
in opposition, and the measure passed with a margin of nineteen votes.
It is significant that nineteen of the twenty votes in opposition were
those of Southern members, the only Northerner in the list being Jonathan
Grout of Massachusetts, a Democrat, who did not return to the next
Congress. Like preceding Hamiltonian measures, this meant the
concentration of the financial resources of the country in the commercial
North to the disadvantage of the agricultural South. But this was not the
only reason. With the Southerners, among whom banks were a rarity, and
the Westerners, to whom they were as meaningless as the canals on Mars,
the advantage of such an institution was not felt. In both sections anything
that hinted of monopoly was abhorrent. Thus, in addition to the
constitutional difference, there was an economic conflict that was sectional
in its nature.

IV

But the battle was not yet won. The conflict was transferred to the
Cabinet, for Washington was not at all convinced that there was no
constitutional prohibition. Not only did he withhold his signature till the last
minute, but there are reasons to believe that he had a veto in mind almost to
the end. For Madison, with whose part in the framing of the Constitution he
was familiar, he had a profound respect. Having discussed the bill with
Jefferson informally, Washington requested written opinions from both
Jefferson and Randolph, the Attorney-General. Both were in complete
accord with the conclusions of Madison. The opinion of Jefferson,
expressed with all his force of reasoning, was a powerful challenge to the
doctrine of implied powers.[301]
It was at about this time that Washington summoned Madison to the
Morris house, which served as the Executive Mansion in Philadelphia, to
invite a fuller expression of his views. The great man listened in silence,
and Madison thought with sympathy, while the little giant of the
Constitutional Convention, out of the wealth of his learning and experience,
poured forth his reasons for opposition. Not once, but several times, the
little figure of Madison must have been seen entering the Morris house in
those days of suppressed excitement, for there were numerous conferences.
As the ten-day period followed for the affixing of the presidential signature
was drawing to an end, and Washington requested his friend to reduce his
objections to writing, Madison assumed that it was a veto message he was
asked to frame. Nor was it a far-fetched assumption, for on more than one
occasion the President had made use of Madison’s pen.[302]
Meanwhile the Hamiltonians, at first puzzled, became alarmed. From the
temper of their talk in Philadelphia, Madison was convinced that in the
event of a veto they were ready for open opposition to Washington, backed
by the wealth and influence of the powerful.[303] Ugly, silly stories,
reflecting upon the great personage on whom the Hamiltonians found it
profitable to claim a monopoly, were set afloat. Fisher Ames gave currency
in Boston to the theory that Washington was influenced by the fear that the
establishment of a financial capital in Philadelphia would prevent the
removal of the political capital to the banks of the stream that washed the
boundary of Mount Vernon.[304] If some discretion was used in
Philadelphia, where the grumbling was confined to the fashionable
drawing-rooms, no such circumspection was observed in New York, where
the meanest motives were ascribed to the President, and among the
speculators and Tory sympathizers open threats were made. Madison heard,
while there a little later, that ‘the licentiousness of [these] tongues exceeded
anything that was conceived.’[305] This struggle marked a definitive break
in the relations of Hamilton and Jefferson. The dictatorial disposition of the
former would brook no opposition, and he was temperamentally incapable
of a differentiation between political opposition and personal hostility. The
fact that Jefferson, in response to a command from Washington, had written
an opinion against the Bank could bear only one interpretation—‘asperity
and ill humor toward me.’[306] The fact that Washington accepted
Hamilton’s view, did not, however, shake Jefferson’s faith in the President,
and in defeat nothing so ill-tempered escaped him as flowed in a stream
from the Federalists when threatened with defeat. Within a month after
Hamilton had won his fight, Jefferson, in commenting to a friend on what
he conceived to be a dangerous trend, wrote that ‘it is fortunate that our first
executive magistrate is purely and zealously republican’—the highest praise
he could bestow.[307]
The press was not verbose in its comments on the bill, albeit Freneau
fought it in the ‘Federal Gazette.’[308] The ‘Pennsylvania Gazette’ was
ungraceful in defeat. Denouncing the Bank as ‘a proposition made to the
moneyed interest,’ it commented on its ‘preparations to subscribe,’ and
found ‘the terms ... so advantageous that no equal object of speculation is
perhaps presented in any quarter of the globe.’[309] Fenno offered his best
in a verse:

‘The States as one agree that this is right


Let pigmy politicians rave and write.’[310]

Thus the First Congress closed its labors with no little rhapsodizing in
the press over the results. A New York paper offered an epitaph of
glorification,[311] which a Boston paper condensed into the simple
comment that it had ‘established public confidence and credit, reconciled
the jarring interests of discontented States, and cemented the people in the
bonds of harmony, peace and love.’[312]
One man, at least, had cause for jubilation. In two years Hamilton had
risen to a position of commanding power, proved his genius in constructive
statesmanship, accomplished everything he had set out to do, made himself
the idol of the wealthy and the powerful, the recognized leader of the
influential commercial class, the acknowledged head of a brilliant and
militant party. His friends were comparing him to Pitt, then in the heyday of
his power—and he was only on the threshold. So great was the enthusiasm
in commercial circles that he made a special trip to New York to accept the
homage of the Chamber of Commerce at a reception, to linger a week
among his worshipers, and to return to Philadelphia reinvigorated by the
wine of idolatry pressed to his lips.[313] At that moment he was on the top
of the world.

Meanwhile, Jefferson and Madison drove out of Philadelphia together on


one of those journeys of recreation during which politicians so often plan
the strategy of war. Historians have found more in this journey than is to be
discovered in the record. The trip through New England probably had no
other object than that of pleasure and enlightenment. The relations of these
two men were beautiful and went far beyond a mere congeniality in
political opinions. There was a marked similarity in their characters. Both
scholarly in their tastes, the books that interested one were certain to appeal

You might also like