Full Chapter Getting Started With Angular 2Nd Edition Stephen Adams PDF
Full Chapter Getting Started With Angular 2Nd Edition Stephen Adams PDF
Full Chapter Getting Started With Angular 2Nd Edition Stephen Adams PDF
https://textbookfull.com/product/getting-started-with-
kubernetes-2nd-edition-baier/
https://textbookfull.com/product/getting-started-with-phantomjs-
beltran-aries/
https://textbookfull.com/product/getting-started-with-r-an-
introduction-for-biologists-2nd-edition-andrew-beckerman/
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/
https://textbookfull.com/product/getting-started-with-eeg-
neurofeedback-john-n-demos/
https://textbookfull.com/product/getting-started-with-
advanced-c-1st-edition-vaskaran-sarcar-sarcar/
https://textbookfull.com/product/getting-started-with-microsoft-
system-center-operations-manager-kevin-greene/
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 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.
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
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
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
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.
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.
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.
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.
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!
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.
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.
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:
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
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.
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
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
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
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
• 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.
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.
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.
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:
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
IX
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:
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
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:
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.