Table Of ContentAngular
Up & Running
LEARNING ANGULAR, STEP BY STEP
Shyam Seshadri
Angular: Up and Running
Learning Angular, Step by Step
Shyam Seshadri
BBeeiijjiinngg BBoossttoonn FFaarrnnhhaamm SSeebbaassttooppooll TTookkyyoo
Angular: Up and Running
By Shyam Seshadri
Copyright © 2018 Shyam Seshadri. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are
also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐
tutional sales department: 800-998-9938 or corporate@oreilly.com.
Acquisitions Editor: Mary Treseler Indexer: Ellen Troutman-Zaig
Developmental Editor: Angela Rufino Interior Designer: David Futato
Production Editor: Kristen Brown Cover Designer: Ellie Volckhausen
Copyeditor: Kim Cofer Illustrator: Rebecca Demarest
Proofreader: Jasmine Kwityn
June 2018: First Edition
Revision History for the First Edition
2018-05-31: First release
See http://oreilly.com/catalog/errata.csp?isbn=9781491999837 for release details.
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Angular: Up and Running, the cover
image, and related trade dress are trademarks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not represent the publisher’s views.
While the publisher and the author have used good faith efforts to ensure that the information and
instructions contained in this work are accurate, the publisher and the author disclaim all responsibility
for errors or omissions, including without limitation responsibility for damages resulting from the use of
or reliance on this work. Use of the information and instructions contained in this work is at your own
risk. If any code samples or other technology this work contains or describes is subject to open source
licenses or the intellectual property rights of others, it is your responsibility to ensure that your use
thereof complies with such licenses and/or rights.
978-1-491-99983-7
[LSI]
Table of Contents
Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
1. Introducing Angular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Why Angular 2
What This Book Will Not Cover 2
Getting Started with Your Development Environment 3
Node.js 3
TypeScript 3
Angular CLI 4
Getting the Codebase 5
Conclusion 5
2. Hello Angular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Starting Your First Angular Project 7
Understanding the Angular CLI 8
Running the Application 9
Basics of an Angular Application 11
Root HTML—index.html 12
The Entry Point—main.ts 12
Main Module—app.module.ts 13
Root Component—AppComponent 14
Creating a Component 16
Steps in Creating New Components 16
Using Our New Component 18
Understanding Data Binding 19
Understanding Property Binding 22
Understanding Event Binding 25
Using Models for Cleaner Code 30
iii
Conclusion 32
Exercise 33
3. Useful Built-In Angular Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Directives and Components 35
Built-In Attribute Directives 36
NgClass 36
NgStyle 40
Alternative Class and Style Binding Syntax 41
Built-In Structural Directives 42
NgIf 44
NgFor 45
NgSwitch 50
Multiple Sibling Structural Directives 51
Conclusion 51
Exercise 52
4. Understanding and Using Angular Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Components—A Recap 53
Defining a Component 54
Selector 54
Template 55
Styles 56
Style Encapsulation 58
Others 59
Components and Modules 61
Input and Output 62
Input 62
Output 64
Change Detection 67
Component Lifecycle 71
Interfaces and Functions 72
View Projection 77
Conclusion 79
Exercise 79
5. Testing Angular Components. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Why Unit Test? 81
Testing and Angular 82
The Test Setup 83
Karma Config 84
test.ts 85
iv | Table of Contents
Writing Unit Tests 85
An Isolated Unit Test 85
Running the Tests 87
Writing an Angular-Aware Unit Test 89
Testing Component Interactions 92
Debugging 95
Conclusion 96
Exercise 96
6. Working with Template-Driven Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Template-Driven Forms 97
Setting Up Forms 98
Alternative to ngModel—Event and Property Binding 99
ngModel 102
A Complete Form 104
Control State 108
Control Validity 112
Working with FormGroups 118
Conclusion 121
Exercise 121
7. Working with Reactive Forms. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Reactive Forms 123
Understanding the Differences 124
Using Reactive Forms 124
Form Controls 124
Form Groups 128
Form Builders 131
Form Data 132
Control State, Validity, and Error Messages 133
Form and Data Model 135
FormArrays 139
Conclusion 145
Exercise 145
8. Angular Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
What Are Angular Services? 147
Creating Our Own Angular Service 148
Digging into the Example 148
An Introduction to Dependency Injection 158
Angular and Dependency Injection 160
RxJS and Observables: Moving to Asynchronous Operations 167
Table of Contents | v
Conclusion 173
Exercise 173
9. Making HTTP Calls in Angular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Introducing HttpClient 175
Server Setup 176
Using HttpClientModule 176
Making HTTP GET/POST Calls 177
Advanced HTTP 183
Options—Headers/Params 184
Options—Observe/Response Type 186
Interceptors 191
Advanced Observables 199
Conclusion 206
Exercise 207
10. Unit Testing Services. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
How to Unit Test Services 209
Testing Components with a Service Dependency 213
Testing Components with a Real Service 213
Testing Components with a Mock Service 214
Testing Components with a Fake Service 216
Unit Testing Async 219
Unit Testing HTTP 222
Conclusion 227
Exercise 228
11. Routing in Angular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Setting Up Angular Routing 229
Server Setup 229
Starting Codebase 230
Importing the Router Module 230
Displaying the Route Contents 233
Navigating Within the Application 234
Wildcards and Defaults 236
Common Routing Requirements 238
Required Route Params 238
Navigating in Your Application 240
Optional Route Params 244
Route Guards 247
Authenticated-Only Routes 248
Preventing Unload 250
vi | Table of Contents
Preloading Data Using Resolve 253
Conclusion 255
Exercise 256
12. Productionizing an Angular App. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Building for Production 259
Production Build 260
Ahead-of-Time (AOT) Compilation and Build Optimizer 261
Base Href 262
Deploying an Angular Application 262
Other Concerns 263
Caching 263
API/Server Calls and CORS 265
Different Environments 266
Handling Deep-Linking 266
Lazy Loading 267
Server-Side Rendering and Handling SEO 274
Conclusion 283
Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Table of Contents | vii
Introduction
It’s funny that we constantly over- or underestimate the impact of certain events and
projects in our lives. I seriously believed that the last project I worked on at Google,
Google Feedback, would end up completely changing how the company interacted
with its customers. And I believed Angular (AngularJS at the time) would just be
another flash-in-the-pan, yet-another-framework that would not outlive the Feed‐
back project’s admin interface.
And in hindsight, it was exactly the other way around. While Feedback still exists and
is baked into a lot of Google products, it is Angular that has gone from a tiny project
used by one internal team at Angular to now being used by thousands of developers
and companies worldwide. And a lot of it stems from Misko, Igor, and the entire team
around it, and their unerring dedication to improving how we develop web applica‐
tions.
What started off as a two-member project is now one of the largest open source com‐
munities on the web, and the framework has impacted and been a part of thousands
of projects across the world. There are dozens of books, hundreds of tutorials, and
thousands of articles on Angular, and Angular’s adoption and support continues to
grow each day.
Some of the major concepts that were ahead of their time during the first version of
Angular (like data binding, separation of concerns, dependency injection, etc.) are
now common features of new frameworks.
The biggest change to the AngularJS ecosystem has been the release of the new ver‐
sion of Angular (initially called Angular 2.0, now just called Angular). It was a drastic,
non-backward-compatible change that almost divided an entire community. But with
community engagement and an open, inclusive team, what could have been a disas‐
trous step turned out to be a much needed overhaul of Angular to bring it to the new
age of web development.
ix