SlideShare a Scribd company logo
Angular Up and Running Learning Angular Step by
Step 1st Edition Shyam Seshadri pdf download
https://ebookgate.com/product/angular-up-and-running-learning-
angular-step-by-step-1st-edition-shyam-seshadri/
Get Instant Ebook Downloads – Browse at https://ebookgate.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats
XML Step by Step Second Edition Step By Step Microsoft
Michael J. Young
https://ebookgate.com/product/xml-step-by-step-second-edition-
step-by-step-microsoft-michael-j-young/
Picture Yourself Learning Microsoft Excel 2010 Step by
Step 1st Edition Deidre Hayes
https://ebookgate.com/product/picture-yourself-learning-
microsoft-excel-2010-step-by-step-1st-edition-deidre-hayes/
Dressmaking Step by Step Alison Smith
https://ebookgate.com/product/dressmaking-step-by-step-alison-
smith/
Picture Yourself Learning Microsoft Word 2010 Step by
Step 1st Edition Diane (Diane Koers) Koers
https://ebookgate.com/product/picture-yourself-learning-
microsoft-word-2010-step-by-step-1st-edition-diane-diane-koers-
koers/
Dermatologic Surgery Step by Step 1st Edition Keyvan
Nouri
https://ebookgate.com/product/dermatologic-surgery-step-by-
step-1st-edition-keyvan-nouri/
Step by Step LASIK Surgery 1st Edition Namrata Sharma
https://ebookgate.com/product/step-by-step-lasik-surgery-1st-
edition-namrata-sharma/
Microsoft Silverlight 4 Step by Step Laurence Moroney
https://ebookgate.com/product/microsoft-silverlight-4-step-by-
step-laurence-moroney/
Step by step Bread 1st American ed Edition Caroline
Bretherton
https://ebookgate.com/product/step-by-step-bread-1st-american-ed-
edition-caroline-bretherton/
PC Markanda Arbitration Step by Step Markanda P C
https://ebookgate.com/product/pc-markanda-arbitration-step-by-
step-markanda-p-c/
Shyam Seshadri
LEARNING ANGULAR, STEP BY STEP
Angular
Up &Running
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
Shyam Seshadri
Angular: Up and Running
Learning Angular, Step by Step
Boston Farnham Sebastopol Tokyo
Beijing Boston Farnham Sebastopol Tokyo
Beijing
978-1-491-99983-7
[LSI]
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
Developmental Editor: Angela Rufino
Production Editor: Kristen Brown
Copyeditor: Kim Cofer
Proofreader: Jasmine Kwityn
Indexer: Ellen Troutman-Zaig
Interior Designer: David Futato
Cover Designer: Ellie Volckhausen
Illustrator: Rebecca Demarest
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.
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
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
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
Truly, what makes Angular a great technology and framework is the community
around it—those who contribute to the core framework, or develop plug-ins for it, as
well as those who use it on a day-to-day basis.
As part of the community, I am truly excited to present this book, and contribute in
my own way to what makes this community great.
Who Should Read This Book
This book is for anyone who is looking to get started with Angular (2.0 and onward),
whether as a side project, as an additional tool, or for their main work. It is expected
that readers are comfortable with JavaScript and HTML before starting this book, but
a basic knowledge of JavaScript should be sufficient to learn Angular. Knowledge of
AngularJS 1.0 is not needed or expected.
We will also use TypeScript, which is the recommended way of developing in Angu‐
lar, but a preliminary knowledge is sufficient to read this book.
We will take it step by step, so relax and have fun learning with me.
Why I Wrote This Book
Angular as a framework has grown immensely, and comes with a large set of features
and capabilities. With a large community behind it, it also comes with an influx of
helpful content. But the help content, tutorials, and guides are either focused only on
particular topics, or sporadic and not necessarily useful for someone getting started.
The aim of this book is to provide a step-by-step guide on getting started with Angu‐
lar. Each concept is provided in a logical, organized fashion, building on top of the
previous one. With so many moving parts and an active community, this book does
not intend to cover each and every aspect, but instead focuses on the core building
blocks in a detailed fashion while letting readers discover the rest on their own.
At the end of the book, you should be familiar with a majority of the Angular frame‐
work, and be able to use Angular to develop your own web applications and use it in
your own projects.
A Word on Web Application Development Today
JavaScript has come a long way, to the point where it is one of the most widely used
and adopted programming languages. Nowadays, it’s rare for web developers to have
to worry about browser inconsistencies and the like, which was the primary reason
for frameworks like jQuery to have existed.
x | Introduction
Frameworks (like Angular and React) are now a very common choice for developing
frontend experiences, and it is rare for anyone nowadays to decide to build a frontend
application without leveraging one.
The advantages of using frameworks are manifold, from reducing boilerplate code, to
providing a consistent structure and layout for developing an application to many
more. The primary intent is always to reduce the time spent on cruft, and focus more
on the major functionality we want to provide. And if it works across browsers (and
platforms, like Android and iOS, in addition to desktop), then more power to it.
Angular (as well as other frameworks) provides this, primarily through some core
fundamentals that are at the heart of the framework, including:
• Powerful templating syntax driven by declarative programming
• Modularity and separation of concerns
• Data binding, and through it, data-driven programming
• Testability and awesome testing support
• Routing and navigation
• And a host of other features, from server-side rendering, to the ability to write
native mobile applications, and much more!
With the help of Angular, we can focus on building amazing experiences, while man‐
aging complexity and maintainability in a seamless fashion.
Navigating This Book
This book aims to walk a developer through each part of Angular, step by step. Each
chapter that introduces a new concept will be immediately followed by a chapter on
how we can unit test it. The book is roughly organized as follows:
• Chapter 1, Introducing Angular, is an introduction to Angular as well as the con‐
cepts behind it. It also covers what it takes to start writing an Angular
application.
• Chapter 2, Hello Angular, walks through creating a very simple Angular applica‐
tion, and diving into how the pieces work together. It also introduces the Angular
CLI.
• Chapter 3, Useful Built-In Angular Directives, digs into the basic built-in Angular
directives (including ngFor, ngIf, etc.) and when and how to use them.
• Chapter 4, Understanding and Using Angular Components, covers Angular com‐
ponents in more detail, as well as the various options available when creating
them. It also covers the basic lifecycle hooks available with components.
Introduction | xi
• Chapter 5, Testing Angular Components, introduces how to unit test angular com‐
ponents using Karma and Jasmine, along with the Angular testing framework.
• Chapter 6, Working with Template-Driven Forms, covers creating and working
with forms in Angular, specifically template-driven forms.
• Chapter 7, Working with Reactive Forms, covers the other way of defining and
working with forms, which is how to create and develop reactive forms.
• Chapter 8, Angular Services, covers Angular services, which includes how to use
built-in Angular services, as well as how and when to define our own Angular
services.
• Chapter 9, Making HTTP Calls in Angular, moves into the server communication
aspect of Angular, and delves into making HTTP calls, as well as some advanced
topics like interceptors and the like.
• Chapter 10, Unit Testing Services, takes a step back and covers unit testing again,
but this time with a focus on unit testing services. This includes testing simple
services and slightly harder cases like asynchronous flows as well as services and
components that make HTTP calls.
• Chapter 11, Routing in Angular, goes in depth into how we can accomplish rout‐
ing in an Angular application and covers the Angular routing module in detail as
well as a majority of its features.
• Chapter 12, Productionizing an Angular App, finally brings together all the con‐
cepts and covers taking the developed Angular application to production and the
various concerns and techniques involved in the same.
The entire code repository is hosted on GitHub, so if you don’t want to type in the
code examples from this book, or want to ensure that you are looking at the latest and
greatest code examples, visit the repository and grab the contents.
This book uses AngularJS version 5.0.0 for all its code examples.
Online Resources
The following resources are a great starting point for any AngularJS developer, and
should be always available at your fingertips:
• The Official Angular API Documentation
• The Official Angular Quickstart Guide
• The Angular Heroes Tutorial App
xii | Introduction
Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions.
Constant width
Used for program listings, as well as within paragraphs to refer to program ele‐
ments such as variable or function names, databases, data types, environment
variables, statements, and keywords.
Constant width bold
Shows commands or other text that should be typed literally by the user.
Constant width italic
Shows text that should be replaced with user-supplied values or by values deter‐
mined by context.
This element signifies a tip or suggestion.
This element signifies a general note.
This element indicates a warning or caution.
Using Code Examples
Supplemental material (code examples, exercises, etc.) is available for download at
https://github.com/shyamseshadri/angular-up-and-running.
This book is here to help you get your job done. In general, if example code is offered
with this book, you may use it in your programs and documentation. You do not
need to contact us for permission unless you’re reproducing a significant portion of
the code. For example, writing a program that uses several chunks of code from this
book does not require permission. Selling or distributing a CD-ROM of examples
Introduction | xiii
from O’Reilly books does require permission. Answering a question by citing this
book and quoting example code does not require permission. Incorporating a signifi‐
cant amount of example code from this book into your product’s documentation does
require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “Angular: Up and Running by Shyam
Seshadri (O’Reilly). Copyright 2018 Shyam Seshadri, 978-1-491-99983-7.”
If you feel your use of code examples falls outside fair use or the permission given
above, feel free to contact us at permissions@oreilly.com.
O’Reilly Safari
Safari (formerly Safari Books Online) is a membership-based
training and reference platform for enterprise, government,
educators, and individuals.
Members have access to thousands of books, training videos, Learning Paths, interac‐
tive tutorials, and curated playlists from over 250 publishers, including O’Reilly
Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐
sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press,
John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe
Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and
Course Technology, among others.
For more information, please visit http://oreilly.com/safari.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at http://bit.ly/angularUR.
To comment or ask technical questions about this book, send email to bookques‐
tions@oreilly.com.
xiv | Introduction
For more information about our books, courses, conferences, and news, see our web‐
site at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia
Acknowledgments
This book is dedicated to my wife, Sanchita, and my parents and grandmom who
were my rock as well as my motivation to write this book in the best manner I could,
all the while balancing my own fledgling startup in its most precarious time (the
beginning!).
I’d also like to thank my reviewers, Yakov Fain and Victor Mejia, who had to read and
review my unedited ramblings and make sure I got my point across in the most suc‐
cinct and understandable terms.
This book of course wouldn’t be possible without the faith and efforts of the awesome
team at O’Reilly, especially Angela and Kristen!
And finally, thank you to the amazing Angular community for all their contributions,
feedback, and support, and for teaching us how to use and make it better.
Introduction | xv
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
CHAPTER 1
Introducing Angular
Our expectations of what we can perform on the web (and by web here, I mean both
desktop as well as the mobile web) has increased to the point where what used to be
full-fledged native desktop applications are run on the browser. Web applications
now resemble desktop native applications in scope and complexity, which also results
in added complexity as a developer.
Furthermore, Single-Page Applications (SPAs) have become a very common choice in
building out frontend experiences, as they allow for great customer experiences in
terms of speed and responsiveness. Once the initial application has loaded into a cus‐
tomer’s browser, further interactions only have to worry about loading the additional
data needed, without reloading the entire page as was the norm with server-side ren‐
dered pages of the past.
AngularJS was started to first bring structure and consistency to single-page web
application development, while providing a way to quickly develop scalable and
maintainable web applications. In the time since it was released, the web and brows‐
ers have moved forward by leaps and bounds, and some of the problems that Angu‐
larJS was solving weren’t as relevant anymore.
Angular then was basically a completely new rewritten version of the framework,
built for the new-age web. It leveraged a lot of the newer advances, from modules to
web components, while improving the existing features of AngularJS, like depend‐
ency injection and templating.
From now on, when I say AngularJS, I refer to the original Angu‐
larJS framework, the 1.0 version. Whenever I mention Angular, it
refers to the newer framework, from 2.0 onward. This is primarily
because Angular 2.0 onward does not predicate itself to using only
JavaScript, but also supports writing applications in TypeScript.
1
Why Angular
Angular as a framework provides a few significant advantages while also providing a
common structure for developers on a team to work with. It allows us to develop
large applications in a maintainable manner. We will dig into each one of these in
more detail in the following chapters:
Custom components
Angular allows you to build your own declarative components that can pack
functionality along with its rendering logic into bite-sized, reusable pieces. It also
plays well with web components.
Data binding
Angular allows you to seamlessly move your data from your core JavaScript code
to the view, and react to view events without having to write the glue code your‐
self.
Dependency injection
Angular allows you to write modular services, and have them injected wherever
they are needed. This greatly improves the testability and reusability of the same.
Testing
Tests are first-class citizens, and Angular has been built from the ground up with
testability in mind. You can (and should!) test every part of your application.
Comprehensive
Angular is a full-fledged framework, and provides out-of-the-box solutions for
server communication, routing within your application, and more.
Angular as a framework has adopted semantic versioning for all
new releases. Furthermore, the core team has an aggressive road‐
map, with a new major release planned every six months. Thus,
what started off as Angular 2 is now referred to as just Angular,
since we don’t want to call them Angular 2, Angular 4, Angular 5,
and so on.
That said, unlike AngularJS to Angular, upgrading between ver‐
sions of Angular (say 2 to 4, etc.) is an incremental step, and more
often than not an almost trivial upgrade. So you don’t need to
worry about having to do a major upgrade every few months with
drastic code changes.
What This Book Will Not Cover
While Angular as a framework is quite large, the community around it is even larger.
A lot of great features and options for use with Angular in fact stem from this
2 | Chapter 1: Introducing Angular
community. This makes life harder as an author to figure out how to write a book
that preps you, the reader, as an Angular developer, while still limiting the scope to
what I think are the essentials.
To that extent, while Angular can be extended in so many ways, from writing native
mobile apps using Angular (see NativeScript), rendering your Angular application on
the server (see Angular Universal), using Redux as a first-class option in Angular
(multiple options; see ngrx), and many more, the initial version of the book will only
focus on the core Angular platform and all the capabilities it provides. It will also
strive to focus on the more common cases rather than cover every single feature and
capability of Angular, as such a book would run into thousands of pages.
The intention is to focus on the parts that will be necessary and useful to all Angular
developers, rather than focus on bits and parts that would be useful to a subset.
Getting Started with Your Development Environment
Angular expects you to do a fair bit of groundwork to be able to develop seamlessly
on your computer. Certain prerequisites need to be installed that we will cover in this
section.
Node.js
While you will never be coding in Node.js, Angular uses Node.js as its base for a large
part of its build environment. Thus, to get started with Angular, you will need to have
Node.js installed on your environment. There are multiple ways to install Node.js, so
please refer to the Node.js Download Page for more instructions.
On macOS, installing Node.js through Homebrew has been known
to cause some issues. So try installing it directly if you run into any
problems.
You need to install version 6.9.0 or above of Node.js, and version 3.0.0 or above of
npm. You can confirm your versions after installing by running the following
commands:
node --version
npm --v
TypeScript
TypeScript adds a set of types to the JavaScript code that we write, allowing us to
write JavaScript that is easier to understand, reason about, and trace. It ensures that
the latest proposed ECMAScript features are also available at the tip of our fingers. At
Getting Started with Your Development Environment | 3
the end of the day, all your TypeScript code compiles down to JavaScript that can run
easily in any environment.
TypeScript is not mandatory for developing an Angular application, but it is highly
recommended, as it offers some syntactic sugar, as well as makes the codebase easier
to understand and maintain. In this book, we will be using TypeScript to develop
Angular applications.
TypeScript is installed as an NPM package, and thus can be simply installed with the
following command:
npm install -g typescript
Make sure you install at least version 2.4.0 or above.
While we will be covering most of the basic features/concepts that we use from Type‐
Script, it is always a good idea to learn more from the official TypeScript documenta‐
tion.
Angular CLI
Unlike AngularJS, where it was easy to source one file as a dependency and be up and
running, Angular has a slightly more complicated setup. To this extent, the Angular
team has created a command-line interface (CLI) tool to make it easier to bootstrap
and develop your Angular applications.
As it significantly helps making the process of development easier, I recommend
using it at the very least for your initial projects until you get the hang of all the things
it does and are comfortable doing it yourself. In this book, we will cover both the CLI
command as well as the actions it performs underneath, so that you get a good
understanding of all the changes needed.
Installing the latest version (1.7.3 at the time of writing this book) is as simple as run‐
ning the following command:
npm install -g @angular/cli
If you are scratching your head at this newfangled naming conven‐
tion for Angular packages, the new syntax is a feature of NPM
called scoped packages. It allows packages to be grouped together
within NPM under a single folder. You can read more here.
Once installed, you can confirm if it was successful by running the following
command:
ng --version
4 | Chapter 1: Introducing Angular
Getting the Codebase
All the examples from this book, along with the exercises and the final solution, are
hosted as a Git repository. While it is not mandatory to download this, you can
choose to do so if you want a reference or want to play around with the samples in
this book. You can do so by cloning the Git repository by running the following
command:
git clone https://github.com/shyamseshadri/angular-up-and-running.git
This will create a folder called angular-up-and-running in your current working direc‐
tory with all the necessary examples. Within this directory you’ll find subfolders con‐
taining the examples, organized by chapter.
Conclusion
At this point, we are all set up with our development environment and are ready to
start developing Angular applications. We have installed Node.js, TypeScript, as well
as the Angular CLI and understand the need and use of each.
In the next chapter, we will finally get our hands dirty building our first Angular
application and understanding some of the basic terms and concepts of Angular.
Conclusion | 5
Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri
CHAPTER 2
Hello Angular
In the previous chapter, we got a very quick overview of Angular and its features, as
well as a step-by-step guide on how to set up our local environment for developing
any Angular application. In this chapter, we will go through the various parts of an
Angular application by creating a very simple application from scratch. Through the
use of this application, we will cover some of the basic terminologies and concepts
like modules, components, data and event binding, and passing data to and from
components.
We will start with a very simple stock market application, which allows us to see a list
of stocks, each with its own name, stock code, and price. During the course of this
chapter, we will see how to package rendering a stock into an individual, reusable
component, and how to work with Angular event and data binding.
Starting Your First Angular Project
As mentioned in the previous chapter, we will heavily rely on the Angular CLI to help
us bootstrap and develop our application. I will assume that you have already fol‐
lowed the initial setup instructions in the previous chapter and have Node.js, Type‐
Script, and the Angular CLI installed in your development environment.
Creating a new application is as simple as running the following command:
ng new stock-market
When you run this command, it will automatically generate a skeleton application
under the folder stock-market with a bunch of files, and install all the necessary
dependencies for the Angular application to work. This might take a while, but even‐
tually, you should see the following line in your terminal:
Project 'stock-market' successfully created.
7
Congratulations, you have just created your first Angular application!
While we created our first application with the vanilla Angular CLI
command, the ng new command takes a few arguments that allow
you to customize the application generated to your preference.
These include:
• Whether you want to use vanilla CSS or SCSS or any other
CSS framework (for example, ng new --style=scss)
• Whether you want to generate a routing module (for example,
ng new --routing); we’ll discuss this further in Chapter 11.
• Whether you want inline styles/templates
• Whether you want a common prefix to all components (for
example, to prefix acme to all components, ng new
--prefix=acme)
And much more. It’s worth exploring these options by running ng
help once you are a bit more familiar with the Angular framework
to decide if you have specific preferences one way or the other.
Understanding the Angular CLI
While we have just created our first Angular application, the Angular CLI does a bit
more than just the initial skeleton creation. In fact, it is useful throughout the devel‐
opment process for a variety of tasks, including:
• Bootstrapping your application
• Serving the application
• Running the tests (both unit and end-to-end)
• Creating a build for distribution
• Generating new components, services, routes and more for your application
Each of these corresponds to one or more Angular CLI commands, and we will cover
each one as and when we need or encounter them, instead of trying to cover each
command and its uses upfront. Each command provides further flexibility with a
variety of arguments and options, making the Angular CLI truly diverse and capable
for a wide variety of uses.
8 | Chapter 2: Hello Angular
Running the Application
Now that we have generated our application, the next part is to run it so that we can
see our live running application in the browser. There are technically two ways to
run it:
• Running it in development mode, where the Angular CLI compiles the changes
as it happens and refreshes our UI
• Running it in production mode, with an optimal compiled build, served via static
files
For now, we will run it in development mode, which is as simple as running
ng serve
from the root folder of the generated project, which is the stock-market folder in this
case. After a little bit of processing and compilation, you should see something like
the following in your terminal:
** NG Live Development Server is listening on localhost:4200,
open your browser on http://localhost:4200/ **
Date: 2018-03-26T10:09:18.869Z
Hash: 0b730a52f97909e2d43a
Time: 11086ms
chunk {inline} inline.bundle.js (inline) 3.85 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 17.9 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 549 kB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 41.5 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 7.42 MB [initial] [rendered]
webpack: Compiled successfully.
The preceding output is a snapshot of all the files that the Angular CLI generates in
order for your Angular application to be served successfully. It includes the
main.bundle.js, which is the transpiled code that is specific to your application, and
the vendor.bundle.js, which includes all the third-party libraries and frameworks you
depend on (including Angular). styles.bundle.js is a compilation of all the CSS styles
that are needed for your application, while polyfills.bundle.js includes all the polyfills
needed for supporting some capabilities in older browsers (like advanced ECMA‐
Script features not yet available in all browsers). Finally, inline.bundle.js is a tiny file
with webpack utilities and loaders that is needed for bootstrapping the application.
ng serve starts a local development server on port 4200 for you to hit from your
browser. Opening http://localhost:4200 in your browser should result in you seeing
the live running Angular application, which should look like Figure 2-1.
Understanding the Angular CLI | 9
Figure 2-1. Hello Angular application in the browser
You can actually leave the ng serve command running in the ter‐
minal, and continue making changes. If you have the application
opened in your browser, it will automatically refresh each time you
save your changes. This makes the development quick and itera‐
tive.
10 | Chapter 2: Hello Angular
In the following section, we will go into a bit more detail about what exactly hap‐
pened under the covers to see how the generated Angular application works and what
the various pieces are.
Basics of an Angular Application
At its core, any Angular application is still a Single-Page Application (SPA), and thus
its loading is triggered by a main request to the server. When we open any URL in
our browser, the very first request is made to our server (which is running within ng
serve in this case). This initial request is satisfied by an HTML page, which then
loads the necessary JavaScript files to load both Angular as well as our application
code and templates.
One thing to note is that although we develop our Angular application in TypeScript,
the web application works with transpiled JavaScript. The ng serve command is
responsible for translating our TypeScript code into JavaScript for the browser to
load.
If we look at the structure the Angular CLI has generated, it is something like this:
stock-market
+----e2e
+----src
+----app
+----app.component.css
+----app.component.html
+----app.component.spec.ts
+----app.component.ts
+----app.module.ts
+----assets
+----environments
+----index.html
+----main.ts
+----.angular-cli.json
Root component
Main module
Root HTML
Entry point
Angular CLI config
There are a few more files than listed here in the stock-market folder, but these are the
major ones we are going to focus on in this chapter. In addition, there are unit tests,
Basics of an Angular Application | 11
end-to-end (e2e) tests, the assets that support our application, configuration specific
to various environments (dev, prod, etc.), and other general configuration that we will
touch upon in Chapters 5, 10, and 12.
Root HTML—index.html
If you take a look at the index.html file, which is in the src folder, you will notice that
it looks very clean and pristine, with no references to any scripts or dependencies:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>StockMarket</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
Root component for our Angular application
The only thing of note in the preceding code is the <app-root> element in the
HTML, which is the marker for loading our application code.
What about the part that loads the core Angular scripts and our application code?
That is inserted dynamically at runtime by the ng serve command, which combines
all the vendor libraries, our application code, the styles, and inline templates each into
individual bundles and injects them into index.html to be loaded as soon as the page
renders in our browser.
The Entry Point—main.ts
The second important part of our bootstrapping piece is the main.ts file. The
index.html file is responsible for deciding which files are to be loaded. The main.ts
file, on the other hand, identifies which Angular module (which we will talk a bit
more about in the following section) is to be loaded when the application starts. It can
also change application-level configuration (like turning off framework-level asserts
and verifications using the enableProdMode() flag), which we will cover in Chap‐
ter 12:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
12 | Chapter 2: Hello Angular
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
Bootstrap the main AppModule
Most of the code in the main.ts file is generic, and you will rarely have to touch or
change this entry point file. Its main aim is to point the Angular framework at the
core module of your application and let it trigger the rest of your application source
code from that point.
Main Module—app.module.ts
This is where your application-specific source code starts from. The application mod‐
ule file can be thought of as the core configuration of your application, from loading
all the relevant and necessary dependencies, declaring which components will be
used within your application, to marking which is the main entry point component of
your application:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
NgModule TypeScript annotation to mark this class definition as an Angular
module
Declarations marking out which components and directives can be used within
the application
Basics of an Angular Application | 13
Importing other modules that provide functionality needed in the application
The entry point component for starting the application
This is our first time dealing with a TypeScript-specific feature,
which are decorators (you can think of them as annotations). Dec‐
orators allow us to decorate classes with annotations and properties
as well as meta-functionality.
Angular heavily leverages this TypeScript feature across the board,
such as using decorators for modules, components, and more.
You can read more about TypeScript decorators in the official doc‐
umentation.
We will go over the details of each of these sections in the following chapters, but at
its core:
declarations
The declarations block defines all the components that are allowed to be used
in the scope of the HTML within this module. Any component that you create
must be declared before it can be used.
imports
You will not create each and every functionality used in the application, and the
imports array allows you to import other Angular application and library mod‐
ules and thus leverage the components, services, and other capabilities that have
already been created in those modules.
bootstrap
The bootstrap array defines the component that acts as the entry point to your
application. If the main component is not added here, your application will not
kick-start, as Angular will not know what elements to look for in your index.html.
You usually end up needing (if you are not using the CLI for any reason!) to modify
this file if and only if you add new components, services, or add/integrate with new
libraries and modules.
Root Component—AppComponent
We finally get to the actual Angular code that drives the functionality of the applica‐
tion, and in this case, it is the main (and only) component we have, the AppCompo
nent. The code for it looks something like this:
14 | Chapter 2: Hello Angular
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
}
The DOM selector that gets translated into an instance of this component
The HTML template backing this component—in this case, the URL to it
Any component-specific styling, again pointing to a separate file in this case
The component class with its own members and functions
A component in Angular is nothing but a TypeScript class, decorated with some
attributes and metadata. The class encapsulates all the data and functionality of the
component, while the decorator specifies how it translates into the HTML.
The app-selector is a CSS selector that identifies how Angular finds this particular
component in any HTML page. While we generally use element selectors (app-root
in the preceding example, which translates to looking for <app-root> elements in the
HTML), they can be any CSS selector, from a CSS class to an attribute as well.
The templateUrl is the path to the HTML used to render this component. We can
also use inline templates instead of specifying a templateUrl like we have done in the
example. In this particular case, the template we are referring to is app.compo‐
nent.html.
styleUrls is the styling counterpart to the template, encapsulating all the styles for
this component. Angular ensures that the styles are encapsulated, so you don’t have to
worry about your CSS classes from one component affecting another. Unlike tem
plateUrl, styleUrls is an array.
The component class itself finally encapsulates all the functionality backing your
component. It makes it easy to think of the responsibilities of the component class as
twofold:
• Load and hold all the data necessary for rendering the component
• Handle and process any events that may arise from any element in the
component
Basics of an Angular Application | 15
The data in the class will drive what can be displayed as part of the component. So
let’s take a look at what the template for this component looks like:
<h1>
{{title}}
</h1>
Data-bound title from the component
Our HTML is as simple as can be for the component. All it has is one element, which
is data-bound to a field in our component class. The double-curly ({{ }}) syntax is
an indication to Angular to replace the value between the braces with the value of the
variable from the corresponding class.
In this case, once the application loads, and the component is rendered, the
{{title}} will be replaced with the text app works!. We will talk in more detail
about data binding in “Understanding Data Binding” on page 19.
Creating a Component
So far, we have dealt with the basic skeleton code that the Angular CLI has generated
for us. Let’s now look at adding new components, and what that entails. We will use
the Angular CLI to generate a new component, but look underneath the covers to see
what steps it takes. We will then walk through some very basic common tasks we try
to accomplish with components.
Steps in Creating New Components
Using the Angular CLI, creating a new component is simply running a simple com‐
mand. We will first try creating a stock widget, which displays the name of the stock,
its stock code, the current price, and whether it has changed for the positive or nega‐
tive.
We can simply create a new stock-item by running the following command from the
main folder of the application:
ng generate component stock/stock-item
There are a few interesting things to note here:
• The Angular CLI has a command called generate, which can be used to generate
components (like we did in the preceding example), and also to generate other
Angular elements, such as interfaces, services, modules, and more.
• With the target type, we also specify the name (and the folder) within which the
component has to be generated. Here, we are telling the Angular CLI to generate
16 | Chapter 2: Hello Angular
a component called stock-item within a folder called stock. If we don’t specify
stock, it will create a component called stock-item in the app folder itself.
The command will generate all the relevant files for a new component, including:
• The component definition (named stock-item.component.ts)
• The corresponding template definition (named stock-item.component.html)
• The styles for the component (in a file named stock-item.component.css)
• The skeleton unit tests for the component (named stock-item.component.spec.ts)
In addition, it updated the original app module that we saw earlier so that our Angu‐
lar application recognizes the new module.
This is the recommended convention to follow whenever you are working with
components:
• The filename starts with the name of the item you are creating
• This is followed by the type of element it is (in this case, a component)
• Finally, we have the relevant extension
This allows us to both group and easily identify relevant and related files in a simple
manner.
When you run the command, you should see something like this:
create src/app/stock/stock-item/stock-item.component.css
create src/app/stock/stock-item/stock-item.component.html
create src/app/stock/stock-item/stock-item.component.spec.ts
create src/app/stock/stock-item/stock-item.component.ts
update src/app/app.module.ts
The source for the component, HTML, and the CSS remain pretty much barebones,
so I won’t repeat that here. What is important is how this new component that we
create is hooked up and made available to our Angular application. Let’s take a look at
the modified app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { StockItemComponent } from './stock/stock-item/stock-item.component';
@NgModule({
declarations: [
AppComponent,
StockItemComponent
],
Creating a Component | 17
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Importing the newly created stock-item component
Adding the new component to the declarations section
In the application module, we have to ensure that the new component is imported
and added to the declarations array, before we can start using it in our Angular
application.
Using Our New Component
Now that we have created a new component, let’s see how we can use it in our appli‐
cation. We will now try to use this skeleton in the app component. First, take a look at
the generated stock-item.component.ts file:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-stock-item',
templateUrl: './stock-item.component.html',
styleUrls: ['./stock-item.component.css']
})
export class StockItemComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
The selector for using this component. Note it is prefixed with app, which is
added by the Angular CLI by default unless otherwise specified.
The component has no data and does not provide any functionality at this point; it
simply renders the template associated with it. The template at this point is also triv‐
ial, and just prints out a static message.
To use this component in our application, we can simply create an element that
matches the selector defined anywhere inside our main app component. If we had
more components and a deeper hierarchy of components, we could choose to use it
in any of their templates as well. So let’s replace most of the placeholder content in
18 | Chapter 2: Hello Angular
app.component.html with the following, so that we can render the stock-item
component:
<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<app-stock-item></app-stock-item>
</div>
Adding our stock-item component
All it takes is adding the <app-stock-item></app-stock-item> to our app.compo‐
nent.html file to use our component. We simply create an element using the selector
we defined in our component. Then when the application loads, Angular recognizes
that the element refers to a component, and triggers the relevant code path.
When you run this (or if your ng serve is still running), you should see both the
original "app works" along with a new "stock-item works" in the UI.
Understanding Data Binding
Next, let’s focus on getting some data and figuring out how to display it as part of our
component. What we are trying to build is a stock widget, which will take some stock
information, and render it accordingly.
Let’s assume that we have a stock for a company named Test Stock Company, with a
stock code of TSC. Its current price is $85, while the previous price it traded at was
$80. In the widget, we want to show both the name and its code, as well as the current
price, the percentage change since last time, and highlight the price and percentage
change in green if it is an increment, or red if it is a decrement.
Let’s walk through this step by step. First, we will make sure we can display the name
and code in the widget (we will hardcode the information for now, and we will build
up the example to get the data from a different source later).
We would change our component code (the stock-item.component.ts file) as follows:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-stock-item',
templateUrl: './stock-item.component.html',
styleUrls: ['./stock-item.component.css']
})
export class StockItemComponent implements OnInit {
public name: string;
public code: string;
Creating a Component | 19
public price: number;
public previousPrice: number;
constructor() { }
ngOnInit() {
this.name = 'Test Stock Company';
this.code = 'TSC';
this.price = 85;
this.previousPrice = 80;
}
}
Implement OnInit interface from Angular, which gives us a hook to when the
component is initialized
Definition of the various fields we will want to access from the HTML
OnInit function that is triggered when a component is initialized
Initializing the values for each of the fields
Angular gives us hooks into the lifecycle of a component to let us take certain actions
when a component is initialized, when its view is rendered, when it is destroyed, and
so on. We’ve extended our trivial component with a few notable things:
OnInit
Angular’s OnInit hook is executed after the component is created by the Angular
framework, after all the data fields are initialized. It is generally recommended to
do any initialization work of a component in the OnInit hook, so that it makes it
easier to test the functionality of the rest of the component without necessarily
triggering the initialization flow every time. We will cover the remaining lifecycle
hooks in Chapter 4.
ngOnInit
When you want to hook on the initialization phase of a component, you need to
implement the OnInit interface (as in the example) and then implement the
ngOnInit function in the component, which is where you write your initializa‐
tion logic. We have initialized the basic information we need to render our stock
widget in the ngOnInit function.
Class member variables
We have declared a few public variables as class instance variables. This informa‐
tion will be used to render our template.
Now, let’s change the template (the stock-item.component.html file) to start rendering
this information:
20 | Chapter 2: Hello Angular
<div class="stock-container">
<div class="name"><h3>{{name}}</h3> - <h4>({{code}})</h4></div>
<div class="price">$ {{price}}</div>
</div>
and its corresponding CSS (the stock-item.component.css file), to make it look nice:
.stock-container {
border: 1px solid black;
border-radius: 5px;
display: inline-block;
padding: 10px;
}
.stock-container .name h3, .stock-container .name h4 {
display: inline-block;
}
Note that the CSS is purely from a visual perspective, and is not
needed nor impacts our Angular application. You could skip it
completely and still have a functional application.
Once we make these changes and refresh our application, we should see something
like Figure 2-2 in our browser.
Figure 2-2. Angular app with stock component
We have just used one fundamental building block from Angular to render our data
from our component into the HTML. We use the double-curly notation ({{ }}),
which is also known as interpolation. Interpolation evaluates the expression between
the curly braces as per the component backing it, and then renders the result as a
Creating a Component | 21
string in place in the HTML. In this case, we render the name, code, and the price of
the stock using interpolation. This picks up the values of name, code, and price, and
then replaces the double-curly expression with its value, thus rendering our UI.
This is Angular’s one-way data binding at work. One-way data binding simply refers
to Angular’s capability to automatically update the UI based on values in the compo‐
nent, and then keeping it updated as the value changes in the component. Without
one-way binding, we would have to write code to take the value from our component,
find the right element in HTML, and update its value. Then we would have to write
listeners/watchers to keep track of when the value in the component changes, and
then change the value in the HTML at that time. We can get rid of all of this extra
code because of data binding.
In this particular case, we are binding to simple variables, but it is not necessarily
restricted to simple variables. The expressions can be slightly more complex. For
example, we could render the same UI by changing the binding expression as follows
in stock-item.component.html:
<div class="stock-container">
<div class="name">{{name + ' (' + code + ')'}}</div>
<div class="price">$ {{price}}</div>
</div>
In this case, we replaced our multiple heading elements with a single div. The interpo‐
lation expression is now a combination of both the name and the code, with the code
surrounded by parentheses. Angular will evaluate this like normal JavaScript, and
return the value of it as a string to our UI.
Understanding Property Binding
So far, we used interpolation to get data from our component code to the HTML. But
Angular also provides a way to bind not just text, but also DOM element properties.
This allows us to modify the content and the behavior of the HTML that is rendered
in the browser.
For example, let’s try to modify our stock widget to highlight the price in red if the
price is less than the previous price, and in green if it is equal to or more than the
previous price. We can first change our component (the stock-item.component.ts) to
precalculate if the difference is positive or negative like so:
22 | Chapter 2: Hello Angular
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-stock-item',
templateUrl: './stock-item.component.html',
styleUrls: ['./stock-item.component.css']
})
export class StockItemComponent implements OnInit {
public name: string;
public code: string;
public price: number;
public previousPrice: number;
public positiveChange: boolean;
constructor() { }
ngOnInit() {
this.name = 'Test Stock Company';
this.code = 'TSC';
this.price = 85;
this.previousPrice = 80;
this.positiveChange = this.price >= this.previousPrice;
}
}
In this code, we added a new public variable called positiveChange, which is of type
boolean, and then set the value based on comparing the current price with the previ‐
ous price. This gives us a singular boolean value that we can use to decide whether to
highlight the price in red or green.
Next, let’s add some classes in the stock-item.component.css file to allow for changing
the color of the text:
.stock-container {
border: 1px solid black;
border-radius: 5px;
display: inline-block;
padding: 10px;
}
.positive {
color: green;
}
.negative {
color: red;
}
We simply added two classes, positive and negative, which change the color of the
text to green and red, respectively. Now let’s tie this together to see how we can use
this information and classes in our stock-item.component.html file:
Creating a Component | 23
<div class="stock-container">
<div class="name">{{name + ' (' + code + ')'}}</div>
<div class="price"
[class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div>
</div>
We have added one new binding on the price div element, which reads as:
[class]="positiveChange ? 'positive' : 'negative'"
This is the Angular syntax for property binding, which binds the value of the expres‐
sion to the DOM property between the square brackets. The [] is the general syntax
that can be used with any property on an element to bind one-way from the compo‐
nent to the UI.
In this particular case, we are telling Angular to bind to the class property of the
DOM element to the value of the expression. Angular will evaluate it like a normal
JavaScript expression, and assign the value (positive in this case) to the class property
of the div element.
When you bind to the class property like we did in the example,
note that it overrides the existing value of the property. In our
example, the "price" class is replaced with the class "positive",
instead of appending to the existing value of the property. You can
notice this for yourself if you inspect the rendered HTML in the
browser. Be careful about this if you bind directly to the class
property.
If the value of the variable positiveChange in the component changes, Angular will
automatically re-evaluate the expression in the HTML and update it accordingly. Try
changing the price so that there is a negative change and then refresh the UI to make
sure it works.
Notice that we have been explicitly referring to the data binding working with DOM
properties, and not HTML attributes. The following sidebar goes into more detail on
the difference between the two, and why it is important to know and understand as
you work on Angular. But simplifying it, Angular data binding only works with
DOM properties, and not with HTML attributes.
HTML Attribute Versus DOM Property: What’s the Difference?
As mentioned, when we work with data binding in Angular, we aren’t working with
HTML attributes but rather DOM properties. Attributes are defined by HTML, while
properties are defined by the Document Object Model. Though some attributes (like
ID and class) directly map to DOM properties, others may exist on one side but not
the other.
24 | Chapter 2: Hello Angular
But more importantly, the distinction between the two is that HTML attributes are
generally used for initialization of a DOM element, but after that, they have no pur‐
pose or effect on the underlying element. Once the element is initialized, its behavior
is controlled by the DOM properties from then on.
For example, consider the input HTML element. If we bootstrap our HTML with
something like:
<input type="text" value="foo"/>
this initializes an input DOM element, with the initial value of the DOM property
value to be set to foo. Now let’s assume we type something in the text box, say bar. At
this point:
• If we do input.getAttribute('value'), it would return foo, which was the
attribute value we used to initialize the HTML.
• If we do input.value, we will get the current value of the DOM property, which
is bar.
That is, the attribute value is used to boostrap and set the initial value of the HTML
DOM element, but after that, it is the DOM property that drives the behavior. If you
inspect the HTML, you will see that it is still the initial HTML we provided, and does
not update either.
In Angular, we thus bind to the DOM property, and not to the HTML attributes.
Whenever we think about one-way binding from the component to the UI, we should
always keep this in mind!
Just like we did for the class property, depending on the use case, we can actually
bind to other HTML properties like the src property of an img tag, or the disabled
property of input and button. We will cover this in more depth in the next chapter.
We will also cover a simpler and more specific way of binding CSS classes in the next
chapter as well.
Understanding Event Binding
So far, we have worked on using the data in our component to both render values and
change the look and feel of our component. In this section, we will start understand‐
ing how to handle user interactions, and work with events and event binding in
Angular.
Say we wanted to have a button that allows users to add the stock to their list of favor‐
ite stocks. Generally, with a button like this, when the user clicks it, we would want to
make some server call and then process the result. So far, since we are working with
Creating a Component | 25
very simple examples, let’s just say we wanted to handle this click and get a hook to it
in our component. Let’s see how we might accomplish that.
First, we can change our component code in stock-item.component.ts to add a func‐
tion toggleFavorite, which should be triggered each time the click happens from
the UI:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-stock-item',
templateUrl: './stock-item.component.html',
styleUrls: ['./stock-item.component.css']
})
export class StockItemComponent implements OnInit {
public name: string;
public code: string;
public price: number;
public previousPrice: number;
public positiveChange: boolean;
public favorite: boolean;
constructor() { }
ngOnInit() {
this.name = 'Test Stock Company';
this.code = 'TSC';
this.price = 85;
this.previousPrice = 80;
this.positiveChange = this.price >= this.previousPrice;
this.favorite = false;
}
toggleFavorite() {
console.log('We are toggling the favorite state for this stock');
this.favorite = !this.favorite;
}
}
We have added a new public boolean member variable called favorite, which is ini‐
tialized with a false value. We then added a new function called toggleFavorite(),
which simply flips the boolean value of favorite. We are also printing a log in the
console to ensure this is getting triggered.
Now, let’s update the UI to use this concept of a favorite and also allow users to tog‐
gle the state:
26 | Chapter 2: Hello Angular
<div class="stock-container">
<div class="name">{{name + ' (' + code + ')'}}</div>
<div class="price"
[class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div>
<button (click)="toggleFavorite()"
[disabled]="favorite">Add to Favorite</button>
</div>
We have added a new button in the stock-item.component.html file to allow users to
click and add the stock to their favorite set. We are using the data-binding concept
from the previous section on the disabled property. Thus, we are disabling the but‐
ton based on the boolean value favorite. If favorite is true, the button will be dis‐
abled, and if it is false, the button will be enabled. Thus, by default, the button is
enabled.
The other major thing we have on the element is this fragment:
(click)="toggleFavorite()"
This syntax is called event binding in Angular. The left part of the equals symbol refers
to the event we are binding to. In this case, it is the click event. Just like how the
square-bracket notation refers to data flowing from the component to the UI, the
parentheses notation refers to events. And the name between the parentheses is the
name of the event we care about.
In this case, we are telling Angular that we are interested in the click event on this
element. The right part of the equals symbol then refers to the template statement
that Angular should execute whenever the event is triggered. In this case, we want it
to execute the new function we created, toggleFavorite.
When we run this application in our browser, we can see the new button. Clicking it
would render something like Figure 2-3.
Notice the other interesting thing, which is Angular data binding at play. When we
click the button, our toggleFavorite function is executed. This flips the value of
favorite from false to true. This in turn triggers the other Angular binding, which
is the disabled property of the button, thus disabling the button after the first click.
We don’t have to do anything extra to get these benefits, which is the beauty of data
binding.
Creating a Component | 27
Discovering Diverse Content Through
Random Scribd Documents
Academy of Sciences was preparing a list of illustrious contemporary
scientists to be submitted to the Kaiser with a view to conferring on them
the badge of the Order of Merit. As Pasteur’s protest and return of his
diploma to the Bonn University had not been forgotten, the Berlin
Academy, before placing his name on the list, desired to know whether he
would accept this distinction at the hands of the German Emperor. Pasteur,
while acknowledging with courteous thanks the honour done to him as a
scientist, declared that he could not accept it.
For him, as for Victor Hugo, the question of Alsace-Lorraine was a
question of humanity; the right of peoples to dispose of themselves was in
question. And by a bitter irony of Fate, France, which had proclaimed this
principle all over Europe, saw Alsace tom away from her. And by whom?
by the very nation whom she had looked upon as the most idealistic, with
whom she had desired an alliance in a noble hope of pacific civilization, a
hope shared by Humboldt, the great German scientist.
It was obvious to those who came near Pasteur that, in spite of the regret
caused in him by the decrease of his physical strength, his moral energy
remained unimpaired. He never complained of the state of his health, and
usually avoided speaking of himself. A little tent had been put up for him in
the new garden of the Pasteur Institute, under the young chestnuts, the
flowers of which were now beginning to fall, and he often spent his
afternoons there. One or other of those who had watched over him through
the long winter nights frequently came to talk with him, and he would
inquire, with all his old interest, into every detail of the work going on.
His old friend Chappuis, now Honorary Rector of the Academy of Dijon,
often came to sit with him under this tent. Their friendship remained
unchanged though it had lasted more than fifty years. Their conversation
now took a yet more exalted turn than in the days of their youth and middle
age. The dignity of Chappuis’ life was almost austere, though tempered by a
smiling philosophy.
Pasteur, less preoccupied than Chappuis by philosophical discussions,
soared without an effort into the domain of spiritual things. Absolute faith
in God and in Eternity, and a conviction that the power for good given to us
in this world will be continued beyond it, were feelings which pervaded his
whole life; the virtues of the Gospel had ever been present to him. Full of
respect for the form of religion which had been that of his forefathers, he
came to it simply and naturally for spiritual help in these last weeks of his
life.
On June 13, he came, for the last time, down the steps of the Pasteur
Institute, and entered the carriage which was to take him to Villeneuve
l’Etang. Every one spoke to him of this stay as if it were sure to bring him
back to health. Did he believe it? Did he try, in his tenderness for those
around him, to share their hopes? His face almost bore the same expression
as when he used to go to Villeneuve l’Etang to continue his studies. When
the carriage passed through Saint Cloud, some of the inhabitants, who had
seen him pass in former years, saluted him with a mixture of emotion and
respectful interest.
At Villeneuve l’Etang, the old stables of the Cent Gardes had reverted to
their former purpose and were used for the preparation of the diphtheria
antitoxin. There were about one hundred horses there; old chargers, sold by
the military authorities as unfit for further work; racehorses thus ending
their days; a few, presents from their owners, such as Marshal Canrobert’s
old horse.
Pasteur spent those summer weeks in his room or under the trees on the
lawns of the Park. A few horses had been put out to grass, the stables being
quite full, and occasionally came near, looking over their hurdles towards
him. Pasteur felt a deep thankfulness in watching the busy comings and
goings of Dr. Roux and his curator, M. Martin, and of the veterinary
surgeon, M. Prévôt, who was entrusted with the bleeding operations and the
distribution of the flasks of serum. He thought of all that would survive him
and felt that his weakened hand might now drop the torch which had set so
many others alight. And, more than resigned, he sat peacefully under a
beautiful group of pines and purple beeches, listening to the readings of
Mme. Pasteur and of his daughter. They smiled on him with that valiant
smile which women know how to keep through deepest anguish.
Biographies interested him as of yore. There was at that time a renewal
of interest in memories of the First Empire; old letters, memoirs, war
anecdotes were being published every day. Pasteur never tired of those great
souvenirs. Many of those stories brought him back to the emotions of his
youth, but he no longer looked with the same eyes on the glory of
conquerors. The true guides of humanity now seemed to him to be those
who gave devoted service, not those who ruled by might. After enjoying
pages full of the thrill of battlefields, Pasteur admired the life of a great and
good man, St. Vincent de Paul. He loved this son of poor peasants, proud to
own his humble birth before a vainglorious society; this tutor of a future
cardinal, who desired to become the chaplain of some unhappy convicts;
this priest, who founded the work of the Enfants Trouvés, and who
established lay and religious alliance over the vast domain of charity.
Pasteur himself exerted a great and charitable influence. The unknown
lady who had put at his disposal four scholarships for young men without
means came to him in August and offered him the funds for a Pasteur
Hospital, the natural outcome, she said, of the Pastorian discoveries.
Pasteur’s strength diminished day by day, he now could hardly walk.
When he was seated in the Park, his grandchildren around him suggested
young rose trees climbing around the trunk of a dying oak. The paralysis
was increasing, and speech was becoming more and more difficult. The
eyes alone remained bright and clear; Pasteur was witnessing the ruin of
what in him was perishable.
How willingly they would have given a moment of their lives to prolong
his, those thousands of human beings whose existence had been saved by
his methods: sick children, women in lying-in hospitals, patients operated
upon in surgical wards, victims of rabid dogs saved from hydrophobia, and
so many others protected against the infinitesimally small! But, whilst
visions of those living beings passed through the minds of his family, it
seemed as if Pasteur already saw those dead ones who, like him, had
preserved absolute faith in the Future Life.
The last week in September he was no longer strong enough to leave his
bed, his weakness was extreme. On September 27, as he was offered a cup
of milk: “I cannot,” he murmured; his eyes looked around him with an
unspeakable expression of resignation, love and farewell. His head fell back
on the pillows, and he slept; but, after this delusive rest, suddenly came the
gaspings of agony. For twenty-four hours he remained motionless, his eyes
closed, his body almost entirely paralyzed; one of his hands rested in that of
Mme. Pasteur, the other held a crucifix.
Thus, surrounded by his family and disciples, in this room of almost
monastic simplicity, on Saturday, September 28, 1895, at 4.40 in the
afternoon, very peacefully, he passed away.
The End.
INDEX
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, Y, Z
A
Abbadie, d’, presents medals to Pasteur, 449
Abdul Aziz, Sultan, 141
About, Edmond:
On Pasteur, 383
On Pasteur’s lecture at Sorbonne, 122
Pamphlet quoted, 177
Académie des Sciences, 29 note, 81
During siege of Paris, 186
Académie Française, Pasteur’s reception at, 345
Aërobes, 99
Agrégation, 31 note
Alais:
Pasteur goes to, 115, 117, 129, 138, 155, 166
Statue to J. B. Dumas at, 446
Alexandria, French mission to, 377
Alfort, experiments on sheep at, 306
Alsace-Lorraine question, 461
Amat, Mlle., 170
Anaërobes, 99, 220
Andral, Dr., 160
Advice to Pasteur, 247
Anglada, work “On Contagion” quoted, 80
Anguillulæ, 150
Anthrax (splenic fever, charbon), 257 seqq., 292
Hens and, 267, 277
Commission on, 278
Vaccination against, 311, 312
Experiment, 315, 317, 318, 320, 328, 367, 368
Results, 325, 367, 368
Antirabic inoculation on man, 414
Discussion on, 434
Anti-vivisection, Virchow on, 332
Aosta, Duke and Duchess of, 141
Arago, 27, 356
On Monge, 195
Speech before Chamber of Deputies, 245
Arbois:
Pasteur at, 6, 7, 180, 420, 437
Presentation to Pasteur from, 449
Prussians at, 202
Arboisian characteristics, 8
Arcis-sur-Aube, battle of, 4
Ardèche, 32
Ardouin, Dr., 380
Aristotle, allusions to hydrophobia, 407
Arsonval, M. d’, 280
Aselli, discoveries through vivisection, 336
Aspartic acid, 57, 70
Aspergillus niger, 204
Aubenas, tribute to Pasteur, 350, 351
Augier, Emile, 174
Aurillac, testimonial to Pasteur, 373
B
“Baccalauréat,” 10 and note
Baciocchi, Princess, leaves Villa Vicentina to Prince Imperial, 173
Bagnères-de-Luchon, 104
Balard, lecturer at Ecole Normale, 29, 31, 56, 59, 100, 106
Advice to Pasteur, 217
Appeal to Pasteur, 217
Discovers bromin, 32
Inspector-General of Higher Education, 145
On Pasteur’s discovery, 40
Bar-sur-Aube, 3rd Regiment at, 3
Barbet Boarding School, 10, 12, 21
Barbet, M., 10, 22
Barbier, Captain, 10
Barrnel, Dumas’ Curator, 25
Bastian, Dr., attacks Pasteur, 253 seqq.
Baudry, Paul, 127
Bazaine at Metz, 186
Beauce, 147 note
Splenic fever in, 257, 276, 284, 314
Béchamp, theory of fermentation, 241
Béclard, Permanent Secretary of Académie de Médecine, 309
On Commission on hydrophobia, 395
Beer, Pasteur studies manufacture of, 207 seqq.
Béhier, Dr., 233
Behring discovers antitoxin for diphtheria, 455
Bellaguet, M., 137
Belle, Jeanne, wife of Claude Pasteur, 2
Bellevue, Château, Napoleon and William of Prussia meet at, 182
Belotti, M., 206
Berchon, sanitary director, Bordeaux, 340
Bergeron, Jules:
Annual Secretary of Académie de Médecine, 309
On Pasteur’s treatment of hydrophobia, 424
Speech at Pasteur Jubilee, 449
Bernard, Claude, 42
At Académie de Médecine, 225
At Tuileries, 154
Discoveries, 135
Experiment on dog, 335
Experiments on fermentation, 280
Illness, 134
Joins in Pasteur’s experiments, 104
Letter to Deville, 137
Letter to Pasteur, 136
On fermentation, 80
— Medicine, 226
— Pasteur’s researches, 72, 87
— Primary causes, 244
— Vivisection, 336
Posthumous notes, 280, 287
Senator, 174
Studies cholera, 126
Bersot, Ernest, quoted on spontaneous generation, 92
Bert, Paul, 279, 374
Classifies Pasteur’s work, 375
Experiments, 263, 392
On Commission on hydrophobia, 395
Speech on Pasteur’s discoveries, 245, 246
Berthelot, M.:
Consulted by Pasteur, 439
On alcoholic fermentation, 286
Berthollet, M., 248, 356
Discoveries, 195
Bertillon, candidate for Académie de Médecine, 225
Bertin, M., 354
At Ecole Normale, 19, 145, 161, 180, 188
Character, 45, 145
Professor of Physics, Strasburg, 45
Welcomes Pasteur to Paris, 212
Bertrand, Joseph:
Letters to Pasteur, 138
Sketch of, 419
Speech at inauguration of Pasteur Institute, 441
Speech at Pasteur Jubilee, 449
Berzelius, 195
Studies paratartaric acid, 25
Theories of fermentation, 80, 241
Besançon, Jean Henri Pasteur at, 2, 4
Besson, candidature for Senate, 249
Beust, Baron von, superintendent of factories, 65
Bigo manufactures beetroot alcohol, 79
Biot, J. J., 27, 42, 55, 59, 204
Attitude towards spontaneous generation, 89, 100
Death, 101, 102
Interview with Pasteur, 41
Last letter, 103
Letters to Joseph Pasteur, 57, 58, 71, 81
Letter to Louis Pasteur, 59
Oldest member of Institute, 81
Passion for reading, 89
Praises Pasteur, 55
Biot, M., veterinary surgeon, at Pouilly le Fort experiment, 316, 320
Bischoffsheim, Raphael, lends villa to Pasteur, 433
Bismarck, Prince:
Armistice with France, 193
Interview with Jules Favre, 184
On Napoleon III, 182
Blondeau, registrar of mortgages, 13
Bollène, Pasteur at, 360
Bonaparte, Elisa, at Villa Vicentina, 173
Bonn, sous-préfecture, 189
University, 189
Bonnat, portrait of Pasteur, 440
Bordeaux, Pasteur at, 338
Bordighera:
Earthquake at, 436
Pasteur at, 434
Borrel attends on Pasteur, 459
Bouchardat, M.:
On Commission of Hygiene, 186
Report on remedies for hydrophobia, 408
Bouillaud, Dr., 229, 262, 294
Bouillier, M. F., Director of Ecole Normale, 145, 180
Bouley, H., 264, 278, 323, 354
At experiment on earthworms, 304
Chairman of Commission on hydrophobia, 395, 396, 397, 398
Report, 398
Death, 424
Letters to Pasteur, 324, 329
— on Colin, 320
— germ of hydrophobia, 398
— methods of Delafond and Pasteur, 275
— microbes, 365, 367
— Pasteur’s treatment of hydrophobia, 423
— remedies for hydrophobia, 408
— virulence of bacteridia, 311
Sketch of, 262
Statistics of death from hydrophobia, 428
Vaccinates sheep against anthrax, 306
Bourbaki, General:
Death, 193
Retreat of Army Corps, 192
Bourboulon, Commandant, gives Pasteur news of his son, 193
Bourgeois, Philibert, 3
Bourrel sends dogs to laboratory, 390, 396
Boussingault, M., 354
Boutet, veterinary surgeon, 261, 283, 329
On splenic fever, 276
Report of vaccinated sheep, 363
Boutroux, curator in Pasteur’s laboratory, 255
Boyle, Robert, on fermentation, 223
Brand, Dr., treatment of typhoid, 364
Breithaupt, Professor of Mineralogy, 65
Bretonneau, on diphtheria, 453
Brie cattle suffer from anthrax, 257, 314
Brochin, candidate for Académie de Médecine, 225
Brongniart, Alexandre, 42
On Commission on spontaneous generation, 106
Brouardel, Professor:
On antirabic cure, 434, 437
Speech at Congress of Hygiene, 446
Speech at Pasteur Jubilee, 449
Broussais, surgery under, 235
Bruce, Mrs., presents Pasteur with Life of Livingstone, 389
Buda-Pesth, Hygiene and Demography Congress at, 456
Budberg, M. de, Russian Ambassador, 127
Budin and antisepsis, 290
Buffon, theory of spontaneous generation, 90
Buonanni, recipe for producing worms, 89
Butyric fermentation, 99
C
Cagniard-Latour studies yeast, 80, 81
Cailletet invents apparatus for liquefaction of gases, 384
Cairo, cholera at, 377
Calmette, Edouard:
At Lille, 461
At Pasteur Jubilee, 447
Attends on Pasteur, 459
Cambon, Governor-General of Algeria, letter to Pasteur, 451
Cardaillac, M. de, 163
Cardinal cultivates silkworms, 139
Carnot, President, 248
At inauguration of Pasteur Institute, 440
At Pasteur Jubilee, 448
Caro, deputy to Edinburgh, 384
Casabianca, Comte de, 168, 169
Celsus on hydrophobia, 407, 409
Chaffois, 192, 193
Chaillou collaborates with Roux, 455
Chamalières brewery, 207
Chamberland, M.:
At Pasteur Jubilee, 447
Collaborates with Pasteur, 260, 269, 271, 283, 289, 303, 305, 306, 308,
311, 317, 319, 321, 359, 420, 424
Cross of Legion of Honour, 326
On Pasteur’s early researches, 445
Vaccinations against anthrax, 440
Chambéry, Pasteur at, 131
Chamecin, wood merchant, 3
Chamonix, Pasteur at, 97
Chantemesse, Dr.:
Attends on Pasteur, 459, 460
On antirabic cure, 434
Performs inoculations, 432
Chanzy, General, open letter, 190
Chappuis, Charles, 33
Letter to Pasteur, 20
On national testimonial to Pasteur, 246
Sketch of, 18
Visits Pasteur, 462
Chaptal, discoveries of, 195
Charbon. (See Anthrax)
Charcot on Pasteur’s antirabic cure, 438
Charrière, schoolfellow of Louis Pasteur, 7, 37
Charrin, Dr., performs inoculations, 432
Chartres:
Experiment on vaccination against anthrax near, 328
Pasteur at, 284, 303
Scientific congress at, 276
Chassaignac, Dr., on “laboratory surgery,” 228
Chauveau on contagion, 366
Chemists and Physicians, 224, 233
Chevreul, M., 59
On siege of Paris, 188, 189
Chicken cholera, 297 seqq.
Chiozza, letter to Pasteur, 200
Cholera, 126
At Damietta and Cairo, 378
Christen, town councillor at Vaucresson, 406
Christophle, speech at inauguration of Pasteur Institute, 441
Clermont Ferrand, Pasteur at, 206
Clouet invents system of manufacturing steel, 195
Coblentz, préfecture, 189
Cochin, Denys, at Pasteur Jubilee, 448
Colin, Professor G., 277, 278
Advice to Biot, 319
Experiments on anthrax, 264, 267, 268
Collège de France, 40 note, 146
Compiègne, Pasteur at, 127
Comte, Auguste, 124, 125
Doctrine, 342
Conseil-Général de département, 78 note
Contagious diseases, problem of, 223 seqq.
Conti, Napoleon III’s secretary, 153
Copenhagen Medical Congress, Pasteur at, 398
Coquelin:
Acts in Plaideurs, 128
Recites at Trocadéro fête, 431
Cornil, on acarus of itch, 366
Coulon, schoolfellow of Louis Pasteur, 7, 36
Cribier, Mme., 161
Cuisance River, 6, 7, 181
Cuvier, 356
D
Daguerre, national testimonial to, 245
Dalimier, Paul, Pasteur’s advice to, 109
Dalloz, editor of Moniteur, 158
Damietta, cholera at, 378
Darboux, “doyen” of Faculty of Science, 31
Daremberg, Dr., on Pasteur at
Medical Congress, 332
Darlay as science master, 14
Darwin:
On earthworms, 304
On vivisection, 337
Dastre, M., 279
Daubrée, speech at Pasteur Jubilee, 449
Daunas, sketch of, 14
David, Jeanne, wife of Denis Pasteur, 1
Davaine, Dr. C., 272, 278, 354
At experiment on earthworms, 304
Experiments on septicæmia, 229, 265
On butyric ferment, 228, 258
Davy, Sir H., 195
Debray, M., 327
Déclat, Dr., on Pasteur’s experiments, 223
Prescribes carbolic solution for wounds, 239
Delafond, Dr.:
On charbon blood, 258
Studies anthrax, 275
Delafosse, Professor of Mineralogy, 33, 36
Delaunay acts in Plaideurs, 128
Delesse, Professor of Science at Besançon, 45
Delort, General Baron, 30
Native of Arbois, 202
Demarquay, Dr., prescribes carbolic solution for wounds, 239
Denmark, King and Queen of, at Medical Congress, 399
Denonvilliers, surgery under, 235
Départements, 52 note
Descartes in Holland, 200
Despeyroux, Professor of Chemistry, 171
Dessaignes, chemist, 70
Deville, Henri Sainte Claire, 42, 45, 137, 160
Admiration for Pasteur’s precision, 287
At Compiègne, 162
At Tuileries, 154
Character, 146
Congratulates Pasteur on Testimonial, 246
Death, 327
Laboratory, 84
Letter to Mme. Pasteur, 174
On Académie and Science, 196
On Commission of Hygiene, 186
Scientific mission in Germany, 179
Studies cholera, 126
Devise, speech at Pasteur Jubilee, 449
Diabetes, 135
Diderot on spontaneous generation, 90
Didon, gratitude to Pasteur, 144, 161
Dieffenbach, M., 335
Dieulafoy, Professor, attends Pasteur, 459
Diphtheria, 453
Statistics of mortality, 456
Disraeli quoted on public health, 446
Dôle:
Jean Joseph Pasteur settles at, 5
Memorial plate on Pasteur’s house at, 376
Presentation to Pasteur from, 450
Douay village, 1
Doucet, Camille, on Pasteur’s speech, 345
Dresden, Pasteur at, 65
Droz, Joseph, his moral doctrine, 16
Dubois, Alphée, engraves medal for Pasteur, 354
Dubois, Paul, 127
Bust of Pasteur, 401
Duboué, Dr., theory on hydrophobia, 393
Duc, Viollet le, 127, 128
Du Camp, Maxime, 346
Duchartre elected member of Académie, 100
Duclaux, M., 102, 103, 104, 131, 138, 169, 170, 204, 205
Accompanies Pasteur to Milan, 250
Advice to Pasteur, 217
Annals of Pasteur Institute, 434
At Pasteur Jubilee, 448
Class of biological chemistry, 440
Congratulates Pasteur on testimonial, 246
On Bastian, 253
On heating liquids, 255
Professor of Chemistry at Clermont Ferrand, 206
Ducret, Antoine and Charles, shot, 202
Ducrot, General, 155
Dujardin-Beaumetz, on antirabic cure, 434
Dumas, Alexandre, 106, 107
Pasteur and, 341
Visits Pasteur, 460
Dumas, J. B., 418
Académie sponsor for Pasteur, 344
Advice to Pasteur, 89, 103
Appreciation of Pasteur, 252
At Alais, 170
Death, 384
Interest in sericiculture, 117
La Vie d’un Savant, 383 note;
letter on, 383
Laboratory, 42
Letter to Bouley, 312
Letters to Pasteur, 60, 166, 169
On Académie and Science, 196
— Commission on spontaneous generation, 106
— Critical Examination, 287
— Destruction of Regnault’s instruments, 191
— Fermentation, 79, 80
Presents Pasteur to Napoleon III, 104
President of Monetary Commission, 145
Requests Pasteur for article on
Lavoisier, 121, 122
Senator, 174
Sketch of, 356
Sorbonne lecturer, 21, 25, 40, 44, 55, 59
Speech at Péclet’s tomb, 328
Speech to Pasteur, 354
Statue at Alais to, 446
Dumont, Dr., 8
Dupuy, Charles, speech at Pasteur Jubilee, 448
Duran, Carolus, portrait of Pasteur, 439
Duruy, M., 106
At inauguration of Pasteur Institute, 441
At Tuileries, 154
Attitude towards Germany, 178
Letter to Pasteur, 139
Minister of Public Instruction, 130
System of National Education, 140
Visits Pasteur, 165
E
Earthworms, pathogenic action of, 304
Eastern Army Corps, 192, 193
Ecole Normale, 10 and note, 154
An ambulance, 180, 188
Disturbances at, 143
Scientific Annals of, 110
Students enlist, 180
Ecole Polytechnique, 43 note, 154
Edelfeldt, portrait of Pasteur, 440
Eggs, researches on alteration of, 231
Ehrenberg, discoveries on infusories, 214
Electric telegraph, birth of, 76
Elsinore, congress visit, 402
Emperor of Brazil, interest in Pasteur’s experiments, 403
Empress Eugénie:
At Bordighera, 436
Interview with Pasteur, 127, 128
Regent, 182
Enfants Malades hospital: diphtheritic treatment at, 455
English commission on inoculation for hydrophobia, 430
Report, 437
Erdmann, M., 64
Exhibition reward distribution, 141
F
Facultés, 31 note
Falloux, attitude towards liberty of teaching, 52
Fauvel, on Pasteur’s inductions, 369
Favé, General, 133, 147, 162, 163
Favre, Jules, Minister of Foreign Affairs, 182
Armistice, 193
Interview with Bismarck, 184
“February days,” 37 note
Feltz on puerperal fever, 292
Fermentation, teaching on, 80, 101, 222, 240
Alcoholic, 85, 104, 113, 286
Butyric, 99, 220, 228, 258
Lactic, 83, 215
of tan, 186
Virus, 223 seqq.
Ferrières Château, interview between Bismarck and Favre at, 184
Fikentscher, obtains racemic acid, 62
Fleming, Mr., 430
On commission on inoculation for hydrophobia, 430
Flesschutt, Dr., 131
Fleys, Dr., proposes toast of Pasteur, 373
Flourens, on spontaneous generation, 105, 106
Fontainebleau, Napoleon at, 4
Formate of strontian crystals, 50
Fortoul, Minister of Public Instruction, 75
Fouqué, M., 327
Fourcroy, M., 248
Discoveries of, 195
Foy, General, works of, 183
Franco-German War, 177 seqq.
Franklin on scientific discovery, 76
Frederic III, sketch of, 330
Frémy, M.:
On origin of ferments, 216, 218
Theory of fermentation, 241
French character, 207
G
Gaidot, Father, 12
Gaillard, M. de, 361
Galen:
Discoveries through vivisection, 336
Remedy for hydrophobia, 407
Galtier, experiments on hydrophobia, 393
Garde Nationale, 37 note
Gardette, M. de la, 361
Gautier, Théophile, 125
Gay-Lussac, 356
Lectures at Jardin des Plantes, 419
Speech before Chamber of Peers, 245
Studies racemic acid, 26
Gayon, researches on alteration of eggs, 231
Geneva Congress of Hygiene, 357
Germs, Pasteur’s theory of, 187
Gernez, M., 104, 161, 166, 169, 170, 327
Centenary of Ecole Normale, 110
Collaborates with Pasteur, 130, 138, 156, 204
Gérôme, Knight of Legion of Honour, 142
Gille, Dr., attends Pasteur, 459
Girard on vineyard labourers and Pasteur, 420
Girardin, St. Marc, 82
Girod, Henry, Royal Notary of Salins, 1
Glénard adopts Brand’s treatment of typhoid, 364
Godélier, Dr., 160
Goltz, M. de, Prussian Ambassador, 127
Gosselin, Dr., 240
Got acts in Plaideurs, 128
Gounod conducts Ave Maria at Trocadéro fête, 431
Grancher, Dr.:
Admiration for Pasteur’s experiments, 417, 424
Advises Pasteur to winter in South, 432
Attends Pasteur, 459
On antirabic cure, 434
Pasteur consults, 415
Performs inoculations, 432
Speech at inauguration of Pasteur Institute, 441
Grandeau, M., 327
Letter to Pasteur, 341
Gravière, Admiral Jurien de la, 433
Gréard, deputy to Edinburgh, 384
Greece, King and Queen of, at Medical Congress, 399
Grenet, Pasteur’s curator, 213
Gressier, M., Minister of Agriculture, 275
Grévy, Jules, supports Tamisier and Thurel, 248
Gridaine, Cunin, Minister of Agriculture, 275
Gsell, Stéphane, on origin of Sériana, 452
Guérin, Alphonse, on cause of purulent infection, 236
Guérin, Jules, on vaccine, 308
Guillaume, Eugène, deputy to Edinburgh, 384
Guillemin, M., 77
Schoolfellow of Louis Pasteur, 7
Guizot, M.:
Deputy to Edinburgh, 384
Quoted on spontaneous generation, 112
Welcomes Biot to Académie, 82
Guyon, Professor:
Accepts Pasteur’s advice, 232
Attends Pasteur, 459
H
Hankel, Professor of Physics at Leipzig, 64
Hardy, M., welcomes Pasteur to Académie de Médecine, 370
Harvey, discoveries through vivisection, 336
Hautefeuille, M., 327
Heated wine, experiments on, 157
Hemiorganism, 216
Henner, portrait of Pasteur, 439
Henri IV plants mulberry trees, 116, 172
Hens and anthrax, 267, 277
Commission on, 278
Héricourt, Dr., 455
At Villeneuve l’Etang, 445
Hervé, Edouard, 427
Heterogenia. (See Spontaneous generation)
Hippocrates, allusions to hydrophobia, 407
Horsley, Victor, secretary to Commission on inoculation for hydrophobia,
431, 437
Houssaye, Henry, on ovation to Pasteur, 426
Hugo, Victor, Année Terrible, 191
Huguenin, portrait of Bonaparte, 181
Humbert of Italy, Prince, 141
Humboldt, Alexander von, interview with J. B. Dumas, 356
Husson, M., 166
Researches on Vaccine, 405
Huxley on Pasteur’s discoveries, 374, 375
Hydrophobia:
Dogs inoculated against, 395;
Commission, 395, 410
English Commission on inoculation for, 430
Report, 437
Experiments on, 318, 363, 383, 390, 410, 422 seqq.
Former remedies, 407
Origin of, 409
Hygiene:
Central Commission, 186
International Congress of, 446
I
Iceland spar, 27
Ingenhousz, 100
Institut de France, 29 note
J
Jacobsen, J. C., founds Carlsberg Brewery, 401
Jacquinet, sub-director of Ecole Normale, 84, 144, 145
Jaillard, experiments on anthrax, 258, 261
Jamin, M., 354
On heterogenist dispute, 111
Jarry, Claude, royal notary, 2
Jenner, national rewards to, 374
Joinville, Prince de, 53 and note
Joly, Nicolas, professor of physiology, Toulouse, 95, 104, 138, 216, 255
Demands Commission on spontaneous generation, 105, 111
Lecture at Faculty of Medicine, 111
Jouassain, Mlle., acts in Plaideurs, 128
Joubert, professor of physics at Collège Rollin, 254, 265, 269, 271
Jourdan, Gabrielle, wife of Jean Henri Pasteur, 2
Journal de la Médecine et de la Chimie quoted, 310
Joux, forest of, 1
Jupille, J. B., bitten by mad dog, 421;
inoculated, 422
K
Kaempfen, director of fine arts, Dôle, 376
Kestner, produces paratartaric acid, 26, 62, 65, 68
Kitasato, discovers antitoxin for diphtheria, 455
Studies plague, 458
Klebs, discovers bacillus of diphtheria, 454
Klein, Dr., pneumo-enteritis of swine, 362
Koch, Dr.:
At Thuillier’s funeral, 381
Campaign against Pasteur, 357, 359, 363, 367
Finds bacillus of tuberculosis, 227
On bacillus anthracis, 259, 260
Studies cholera, 379, 382
Kuhn, Chamalières brewer, 207
L
Laboratories, 42, 84, 153
Lachadenède, M. de, 121, 171
Lactic fermentation, 83, 99
Lagrange, quoted on Lavoisier’s execution, 195
Lamartine, 36 and note
Lambert, Françoise, wife of Claude Etienne Pasteur, 2
Lamy, Auguste, 161
Landouzy, on ambulance ward (1870), 235
Lannelongue, Dr., 289, 391
Laplace, M., 356
Lapparent, M. de, Chairman of Commission on wine, 156, 157
Larrey Baron, 309
On Jupille and Pasteur’s discovery, 423
Surgery under, 235, 240
Laubespin, Comte de, 427
Lauder-Brunton, Dr., on Commission on inoculation for hydrophobia, 430
Laurent, Auguste, 55
Sketch of, 31, 33
Laurent, Madame, 47
Laurent, Maria. (See Pasteur, Mme. Louis)
Laurent, M., Rector of Academy of Strasburg, 47, 156
Sketch of, 47, 54
Lavoisier, death, 195
Edition of his works, 122
Le Bel, studies on stereo-chemistry, 445
Le Dantec, studies on yellow fever in Brazil, 461
Le Fort, Léon:
On puerperal fever, 290
Surgery under, 235, 270
Le Roux, Dissertation sur la Rage, 407
Le Verrier, 129 note, 131
Leblanc, statistics of deaths from hydrophobia, 428
Lechartier, M., 104, 327
Lefebvre, General, 4
Lefort, Mayor of Arbois, 202
Lemaire, Jules, prescribes carbolic solution for wounds, 239
Lemuy, situation of, 1
Leplat, experiments on anthrax, 258, 261
Lereboullet, on anthrax, 269
Lesseps, Ferdinand de, 142
Deputy to Edinburgh, 384
Leval Division:
At Arcis-sur-Aube, 4
At Bar-sur-Aube, 3
Lhéritier, candidate for Académie de Médecine, 225
Liberty of teaching, law on, 52
Liebig:
Ideas on fermentation, 175, 215, 222
Interview with Pasteur, 176
Theory of fermentation, 80, 81, 241
Lille:
Pasteur Dean of Faculté at, 75
Pasteur Institute at, 461
Lister, Sir Joseph:
Appreciation of Pasteur, 252
At Pasteur Jubilee, 449
Letter to Pasteur, 238
Method of surgery, 238, 239
On Commission on inoculation for hydrophobia, 430
Surgical method, 187, 216
Littré:
Medicine and Physicians, 294
On Microbe, 267
On primary causes, 244
Sketch of, 342
Loeffler, isolates bacillus of diphtheria, 454
Loir, Adrien, 54, 58, 360, 362, 402
Dean of Lyons Faculty of Science, 194
Head of Pasteur Institute, Tunis, 461
London, Pasteur visits, 210
London Medical Congress, Pasteur at, 329
London Society for Protection of Animals, complaints on vivisection, 336
Longet, Dr., Treatise on Physiology, 127
Lons-le-Saulnier, 192, 248
Louis XI introduces mulberry tree into Touraine, 116
Louis XVI, 171
Proposal for balloon ascent, 405
Lucas-Championnière, Just:
Edits Journal de la Médecine, 310
On dressing of wounds, 238
Lycée St. Louis, 11, 21, 22
Lyons, Pasteur at, 194
Lyons Commission on silkworm disease, 170
M
MacDonald, General, 4
Magendie, M.:
Experiment with rabic blood, 392
Interview with Quaker, 334
Maillot, M.:
Accompanies Pasteur to Milan, 249
Collaborates with Pasteur, 130, 138, 166, 169
Mairet, Bousson de, sketch of, 8
Maisonneuve, Dr., prescribes carbolic solution for wounds, 239
Malic acid, optical study of, 57, 59
Malus, Etienne Louis, discovers polarization of light, 27
Marat, conduct to Lavoisier, 195
Marchoux, attends on Pasteur, 459
Marcou, geologist, 161
Marie, Dr., attends on Pasteur, 459
Marie, Grand Duchess of Russia, 141
Marmier, attends on Pasteur, 459
Marnoz, Jean Joseph, Pasteur at, 6
Martin, M.:
Attends on Pasteur, 459
Collaborates with Roux, 455
Lecture on diphtheria, 457
Maternité, mortality at, 290
Mathilde, Princesse, 107
Salon, 125
Maucuer, at Bollène, 360
Maunory, M., 284, 303
Maury, A., 137
Medici, Catherine de, plants mulberry tree in Orléannais, 116
Medicine, general condition (1873), 226, 233
Meissonier, Knight of Legion of Honour, 142
Meister, Joseph, 432
Bitten by mad dog, 414
Inoculated, 415, 429
Melun Agricultural Society, tribute to Pasteur, 350
Melun, experiment on vaccination of anthrax near, 314, 316
Méricourt, Le Roy de, 225
Méry, on anatomists, 226
Mesnil, M. du, 163
Attends on Pasteur, 459
Metchnikoff:
At Pasteur Jubilee, 448
Directs private laboratories, 440
Work on “leucocytes,” 458
Metz surrendered, 185
Meudon, proposed laboratory at, 398
Mézières, mission to Edinburgh, 384
Michelet quoted on his friendship with Poinsat, 18
Microbe:
Rossignol on, 314
Word invented, 266
Microscope, results of its invention, 90
Mièges, near Nozeroy, registers of, 1
Milan Congress of Sericiculture, Pasteur at, 249
Miller, M., 66
Milne-Edwards:
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookgate.com

More Related Content

Similar to Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri (20)

PDF
Angular js
Felixits
 
ODP
Angular 6 - The Complete Guide
Sam Dias
 
PDF
Learn Angular 9/8 In Easy Steps
Ahmed Bouchefra
 
PDF
Mastering angular - Dot Net Tricks
Gaurav Singh
 
PDF
Download full ebook of Become a ninja with Angular Ninja Squad instant downlo...
midhoojaben
 
PDF
AngularJS HTML Enhanced For Web Apps
Sharon Collins
 
PPTX
Fly High With Angular - How to build an app using Angular
Vacation Labs
 
PDF
Angular Roadmap For Beginner PDF By ScholarHat.pdf
Scholarhat
 
PPT
Mastering Angular: A Comprehensive Guide
Jay Verma
 
PDF
Download full ebook of Become a ninja with Angular Ninja Squad instant downlo...
tummasakada
 
PPTX
AngularJS One Day Workshop
Shyam Seshadri
 
PDF
Angular Web App Development
philipthomas428223
 
PPTX
Angular 18 course for begineers and experienced
tejaswinimysoola
 
PDF
Angular training-course-syllabus
Training Institute
 
PPTX
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
PDF
Angular 7 training_topics
AmanCSE1
 
PDF
Mean stack training-course-content
Training Institute
 
PPTX
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 
PDF
Angular training-course-syllabus
Training Institute
 
PPTX
The Basics Angular JS
OrisysIndia
 
Angular js
Felixits
 
Angular 6 - The Complete Guide
Sam Dias
 
Learn Angular 9/8 In Easy Steps
Ahmed Bouchefra
 
Mastering angular - Dot Net Tricks
Gaurav Singh
 
Download full ebook of Become a ninja with Angular Ninja Squad instant downlo...
midhoojaben
 
AngularJS HTML Enhanced For Web Apps
Sharon Collins
 
Fly High With Angular - How to build an app using Angular
Vacation Labs
 
Angular Roadmap For Beginner PDF By ScholarHat.pdf
Scholarhat
 
Mastering Angular: A Comprehensive Guide
Jay Verma
 
Download full ebook of Become a ninja with Angular Ninja Squad instant downlo...
tummasakada
 
AngularJS One Day Workshop
Shyam Seshadri
 
Angular Web App Development
philipthomas428223
 
Angular 18 course for begineers and experienced
tejaswinimysoola
 
Angular training-course-syllabus
Training Institute
 
AngularJS with TypeScript and Windows Azure Mobile Services
Rainer Stropek
 
Angular 7 training_topics
AmanCSE1
 
Mean stack training-course-content
Training Institute
 
4 Anguadasdfasdasdfasdfsdfasdfaslar (1).pptx
tilejak773
 
Angular training-course-syllabus
Training Institute
 
The Basics Angular JS
OrisysIndia
 

Recently uploaded (20)

PPTX
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PDF
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
Introduction to Indian Writing in English
Trushali Dodiya
 
PDF
Workbook de Inglés Completo - English Path.pdf
shityouenglishpath
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PPTX
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
PDF
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
PPT-Q1-WK-3-ENGLISH Revised Matatag Grade 3.pptx
reijhongidayawan02
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
epi editorial commitee meeting presentation
MIPLM
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
STATEMENT-BY-THE-HON.-MINISTER-FOR-HEALTH-ON-THE-COVID-19-OUTBREAK-AT-UG_revi...
nservice241
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
Introduction to Indian Writing in English
Trushali Dodiya
 
Workbook de Inglés Completo - English Path.pdf
shityouenglishpath
 
Controller Request and Response in Odoo18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
How to Create a Customer From Website in Odoo 18.pptx
Celine George
 
WATERSHED MANAGEMENT CASE STUDIES - ULUGURU MOUNTAINS AND ARVARI RIVERpdf
Ar.Asna
 
Ad

Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri

  • 1. Angular Up and Running Learning Angular Step by Step 1st Edition Shyam Seshadri pdf download https://ebookgate.com/product/angular-up-and-running-learning- angular-step-by-step-1st-edition-shyam-seshadri/ Get Instant Ebook Downloads – Browse at https://ebookgate.com
  • 2. Get Your Digital Files Instantly: PDF, ePub, MOBI and More Quick Digital Downloads: PDF, ePub, MOBI and Other Formats XML Step by Step Second Edition Step By Step Microsoft Michael J. Young https://ebookgate.com/product/xml-step-by-step-second-edition- step-by-step-microsoft-michael-j-young/ Picture Yourself Learning Microsoft Excel 2010 Step by Step 1st Edition Deidre Hayes https://ebookgate.com/product/picture-yourself-learning- microsoft-excel-2010-step-by-step-1st-edition-deidre-hayes/ Dressmaking Step by Step Alison Smith https://ebookgate.com/product/dressmaking-step-by-step-alison- smith/ Picture Yourself Learning Microsoft Word 2010 Step by Step 1st Edition Diane (Diane Koers) Koers https://ebookgate.com/product/picture-yourself-learning- microsoft-word-2010-step-by-step-1st-edition-diane-diane-koers- koers/
  • 3. Dermatologic Surgery Step by Step 1st Edition Keyvan Nouri https://ebookgate.com/product/dermatologic-surgery-step-by- step-1st-edition-keyvan-nouri/ Step by Step LASIK Surgery 1st Edition Namrata Sharma https://ebookgate.com/product/step-by-step-lasik-surgery-1st- edition-namrata-sharma/ Microsoft Silverlight 4 Step by Step Laurence Moroney https://ebookgate.com/product/microsoft-silverlight-4-step-by- step-laurence-moroney/ Step by step Bread 1st American ed Edition Caroline Bretherton https://ebookgate.com/product/step-by-step-bread-1st-american-ed- edition-caroline-bretherton/ PC Markanda Arbitration Step by Step Markanda P C https://ebookgate.com/product/pc-markanda-arbitration-step-by- step-markanda-p-c/
  • 4. Shyam Seshadri LEARNING ANGULAR, STEP BY STEP Angular Up &Running
  • 6. Shyam Seshadri Angular: Up and Running Learning Angular, Step by Step Boston Farnham Sebastopol Tokyo Beijing Boston Farnham Sebastopol Tokyo Beijing
  • 7. 978-1-491-99983-7 [LSI] 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 [email protected]. Acquisitions Editor: Mary Treseler Developmental Editor: Angela Rufino Production Editor: Kristen Brown Copyeditor: Kim Cofer Proofreader: Jasmine Kwityn Indexer: Ellen Troutman-Zaig Interior Designer: David Futato Cover Designer: Ellie Volckhausen Illustrator: Rebecca Demarest 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.
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 14. 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
  • 15. Truly, what makes Angular a great technology and framework is the community around it—those who contribute to the core framework, or develop plug-ins for it, as well as those who use it on a day-to-day basis. As part of the community, I am truly excited to present this book, and contribute in my own way to what makes this community great. Who Should Read This Book This book is for anyone who is looking to get started with Angular (2.0 and onward), whether as a side project, as an additional tool, or for their main work. It is expected that readers are comfortable with JavaScript and HTML before starting this book, but a basic knowledge of JavaScript should be sufficient to learn Angular. Knowledge of AngularJS 1.0 is not needed or expected. We will also use TypeScript, which is the recommended way of developing in Angu‐ lar, but a preliminary knowledge is sufficient to read this book. We will take it step by step, so relax and have fun learning with me. Why I Wrote This Book Angular as a framework has grown immensely, and comes with a large set of features and capabilities. With a large community behind it, it also comes with an influx of helpful content. But the help content, tutorials, and guides are either focused only on particular topics, or sporadic and not necessarily useful for someone getting started. The aim of this book is to provide a step-by-step guide on getting started with Angu‐ lar. Each concept is provided in a logical, organized fashion, building on top of the previous one. With so many moving parts and an active community, this book does not intend to cover each and every aspect, but instead focuses on the core building blocks in a detailed fashion while letting readers discover the rest on their own. At the end of the book, you should be familiar with a majority of the Angular frame‐ work, and be able to use Angular to develop your own web applications and use it in your own projects. A Word on Web Application Development Today JavaScript has come a long way, to the point where it is one of the most widely used and adopted programming languages. Nowadays, it’s rare for web developers to have to worry about browser inconsistencies and the like, which was the primary reason for frameworks like jQuery to have existed. x | Introduction
  • 16. Frameworks (like Angular and React) are now a very common choice for developing frontend experiences, and it is rare for anyone nowadays to decide to build a frontend application without leveraging one. The advantages of using frameworks are manifold, from reducing boilerplate code, to providing a consistent structure and layout for developing an application to many more. The primary intent is always to reduce the time spent on cruft, and focus more on the major functionality we want to provide. And if it works across browsers (and platforms, like Android and iOS, in addition to desktop), then more power to it. Angular (as well as other frameworks) provides this, primarily through some core fundamentals that are at the heart of the framework, including: • Powerful templating syntax driven by declarative programming • Modularity and separation of concerns • Data binding, and through it, data-driven programming • Testability and awesome testing support • Routing and navigation • And a host of other features, from server-side rendering, to the ability to write native mobile applications, and much more! With the help of Angular, we can focus on building amazing experiences, while man‐ aging complexity and maintainability in a seamless fashion. Navigating This Book This book aims to walk a developer through each part of Angular, step by step. Each chapter that introduces a new concept will be immediately followed by a chapter on how we can unit test it. The book is roughly organized as follows: • Chapter 1, Introducing Angular, is an introduction to Angular as well as the con‐ cepts behind it. It also covers what it takes to start writing an Angular application. • Chapter 2, Hello Angular, walks through creating a very simple Angular applica‐ tion, and diving into how the pieces work together. It also introduces the Angular CLI. • Chapter 3, Useful Built-In Angular Directives, digs into the basic built-in Angular directives (including ngFor, ngIf, etc.) and when and how to use them. • Chapter 4, Understanding and Using Angular Components, covers Angular com‐ ponents in more detail, as well as the various options available when creating them. It also covers the basic lifecycle hooks available with components. Introduction | xi
  • 17. • Chapter 5, Testing Angular Components, introduces how to unit test angular com‐ ponents using Karma and Jasmine, along with the Angular testing framework. • Chapter 6, Working with Template-Driven Forms, covers creating and working with forms in Angular, specifically template-driven forms. • Chapter 7, Working with Reactive Forms, covers the other way of defining and working with forms, which is how to create and develop reactive forms. • Chapter 8, Angular Services, covers Angular services, which includes how to use built-in Angular services, as well as how and when to define our own Angular services. • Chapter 9, Making HTTP Calls in Angular, moves into the server communication aspect of Angular, and delves into making HTTP calls, as well as some advanced topics like interceptors and the like. • Chapter 10, Unit Testing Services, takes a step back and covers unit testing again, but this time with a focus on unit testing services. This includes testing simple services and slightly harder cases like asynchronous flows as well as services and components that make HTTP calls. • Chapter 11, Routing in Angular, goes in depth into how we can accomplish rout‐ ing in an Angular application and covers the Angular routing module in detail as well as a majority of its features. • Chapter 12, Productionizing an Angular App, finally brings together all the con‐ cepts and covers taking the developed Angular application to production and the various concerns and techniques involved in the same. The entire code repository is hosted on GitHub, so if you don’t want to type in the code examples from this book, or want to ensure that you are looking at the latest and greatest code examples, visit the repository and grab the contents. This book uses AngularJS version 5.0.0 for all its code examples. Online Resources The following resources are a great starting point for any AngularJS developer, and should be always available at your fingertips: • The Official Angular API Documentation • The Official Angular Quickstart Guide • The Angular Heroes Tutorial App xii | Introduction
  • 18. Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context. This element signifies a tip or suggestion. This element signifies a general note. This element indicates a warning or caution. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/shyamseshadri/angular-up-and-running. This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples Introduction | xiii
  • 19. from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Angular: Up and Running by Shyam Seshadri (O’Reilly). Copyright 2018 Shyam Seshadri, 978-1-491-99983-7.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected]. O’Reilly Safari Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals. Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others. For more information, please visit http://oreilly.com/safari. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/angularUR. To comment or ask technical questions about this book, send email to bookques‐ [email protected]. xiv | Introduction
  • 20. For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments This book is dedicated to my wife, Sanchita, and my parents and grandmom who were my rock as well as my motivation to write this book in the best manner I could, all the while balancing my own fledgling startup in its most precarious time (the beginning!). I’d also like to thank my reviewers, Yakov Fain and Victor Mejia, who had to read and review my unedited ramblings and make sure I got my point across in the most suc‐ cinct and understandable terms. This book of course wouldn’t be possible without the faith and efforts of the awesome team at O’Reilly, especially Angela and Kristen! And finally, thank you to the amazing Angular community for all their contributions, feedback, and support, and for teaching us how to use and make it better. Introduction | xv
  • 22. CHAPTER 1 Introducing Angular Our expectations of what we can perform on the web (and by web here, I mean both desktop as well as the mobile web) has increased to the point where what used to be full-fledged native desktop applications are run on the browser. Web applications now resemble desktop native applications in scope and complexity, which also results in added complexity as a developer. Furthermore, Single-Page Applications (SPAs) have become a very common choice in building out frontend experiences, as they allow for great customer experiences in terms of speed and responsiveness. Once the initial application has loaded into a cus‐ tomer’s browser, further interactions only have to worry about loading the additional data needed, without reloading the entire page as was the norm with server-side ren‐ dered pages of the past. AngularJS was started to first bring structure and consistency to single-page web application development, while providing a way to quickly develop scalable and maintainable web applications. In the time since it was released, the web and brows‐ ers have moved forward by leaps and bounds, and some of the problems that Angu‐ larJS was solving weren’t as relevant anymore. Angular then was basically a completely new rewritten version of the framework, built for the new-age web. It leveraged a lot of the newer advances, from modules to web components, while improving the existing features of AngularJS, like depend‐ ency injection and templating. From now on, when I say AngularJS, I refer to the original Angu‐ larJS framework, the 1.0 version. Whenever I mention Angular, it refers to the newer framework, from 2.0 onward. This is primarily because Angular 2.0 onward does not predicate itself to using only JavaScript, but also supports writing applications in TypeScript. 1
  • 23. Why Angular Angular as a framework provides a few significant advantages while also providing a common structure for developers on a team to work with. It allows us to develop large applications in a maintainable manner. We will dig into each one of these in more detail in the following chapters: Custom components Angular allows you to build your own declarative components that can pack functionality along with its rendering logic into bite-sized, reusable pieces. It also plays well with web components. Data binding Angular allows you to seamlessly move your data from your core JavaScript code to the view, and react to view events without having to write the glue code your‐ self. Dependency injection Angular allows you to write modular services, and have them injected wherever they are needed. This greatly improves the testability and reusability of the same. Testing Tests are first-class citizens, and Angular has been built from the ground up with testability in mind. You can (and should!) test every part of your application. Comprehensive Angular is a full-fledged framework, and provides out-of-the-box solutions for server communication, routing within your application, and more. Angular as a framework has adopted semantic versioning for all new releases. Furthermore, the core team has an aggressive road‐ map, with a new major release planned every six months. Thus, what started off as Angular 2 is now referred to as just Angular, since we don’t want to call them Angular 2, Angular 4, Angular 5, and so on. That said, unlike AngularJS to Angular, upgrading between ver‐ sions of Angular (say 2 to 4, etc.) is an incremental step, and more often than not an almost trivial upgrade. So you don’t need to worry about having to do a major upgrade every few months with drastic code changes. What This Book Will Not Cover While Angular as a framework is quite large, the community around it is even larger. A lot of great features and options for use with Angular in fact stem from this 2 | Chapter 1: Introducing Angular
  • 24. community. This makes life harder as an author to figure out how to write a book that preps you, the reader, as an Angular developer, while still limiting the scope to what I think are the essentials. To that extent, while Angular can be extended in so many ways, from writing native mobile apps using Angular (see NativeScript), rendering your Angular application on the server (see Angular Universal), using Redux as a first-class option in Angular (multiple options; see ngrx), and many more, the initial version of the book will only focus on the core Angular platform and all the capabilities it provides. It will also strive to focus on the more common cases rather than cover every single feature and capability of Angular, as such a book would run into thousands of pages. The intention is to focus on the parts that will be necessary and useful to all Angular developers, rather than focus on bits and parts that would be useful to a subset. Getting Started with Your Development Environment Angular expects you to do a fair bit of groundwork to be able to develop seamlessly on your computer. Certain prerequisites need to be installed that we will cover in this section. Node.js While you will never be coding in Node.js, Angular uses Node.js as its base for a large part of its build environment. Thus, to get started with Angular, you will need to have Node.js installed on your environment. There are multiple ways to install Node.js, so please refer to the Node.js Download Page for more instructions. On macOS, installing Node.js through Homebrew has been known to cause some issues. So try installing it directly if you run into any problems. You need to install version 6.9.0 or above of Node.js, and version 3.0.0 or above of npm. You can confirm your versions after installing by running the following commands: node --version npm --v TypeScript TypeScript adds a set of types to the JavaScript code that we write, allowing us to write JavaScript that is easier to understand, reason about, and trace. It ensures that the latest proposed ECMAScript features are also available at the tip of our fingers. At Getting Started with Your Development Environment | 3
  • 25. the end of the day, all your TypeScript code compiles down to JavaScript that can run easily in any environment. TypeScript is not mandatory for developing an Angular application, but it is highly recommended, as it offers some syntactic sugar, as well as makes the codebase easier to understand and maintain. In this book, we will be using TypeScript to develop Angular applications. TypeScript is installed as an NPM package, and thus can be simply installed with the following command: npm install -g typescript Make sure you install at least version 2.4.0 or above. While we will be covering most of the basic features/concepts that we use from Type‐ Script, it is always a good idea to learn more from the official TypeScript documenta‐ tion. Angular CLI Unlike AngularJS, where it was easy to source one file as a dependency and be up and running, Angular has a slightly more complicated setup. To this extent, the Angular team has created a command-line interface (CLI) tool to make it easier to bootstrap and develop your Angular applications. As it significantly helps making the process of development easier, I recommend using it at the very least for your initial projects until you get the hang of all the things it does and are comfortable doing it yourself. In this book, we will cover both the CLI command as well as the actions it performs underneath, so that you get a good understanding of all the changes needed. Installing the latest version (1.7.3 at the time of writing this book) is as simple as run‐ ning the following command: npm install -g @angular/cli If you are scratching your head at this newfangled naming conven‐ tion for Angular packages, the new syntax is a feature of NPM called scoped packages. It allows packages to be grouped together within NPM under a single folder. You can read more here. Once installed, you can confirm if it was successful by running the following command: ng --version 4 | Chapter 1: Introducing Angular
  • 26. Getting the Codebase All the examples from this book, along with the exercises and the final solution, are hosted as a Git repository. While it is not mandatory to download this, you can choose to do so if you want a reference or want to play around with the samples in this book. You can do so by cloning the Git repository by running the following command: git clone https://github.com/shyamseshadri/angular-up-and-running.git This will create a folder called angular-up-and-running in your current working direc‐ tory with all the necessary examples. Within this directory you’ll find subfolders con‐ taining the examples, organized by chapter. Conclusion At this point, we are all set up with our development environment and are ready to start developing Angular applications. We have installed Node.js, TypeScript, as well as the Angular CLI and understand the need and use of each. In the next chapter, we will finally get our hands dirty building our first Angular application and understanding some of the basic terms and concepts of Angular. Conclusion | 5
  • 28. CHAPTER 2 Hello Angular In the previous chapter, we got a very quick overview of Angular and its features, as well as a step-by-step guide on how to set up our local environment for developing any Angular application. In this chapter, we will go through the various parts of an Angular application by creating a very simple application from scratch. Through the use of this application, we will cover some of the basic terminologies and concepts like modules, components, data and event binding, and passing data to and from components. We will start with a very simple stock market application, which allows us to see a list of stocks, each with its own name, stock code, and price. During the course of this chapter, we will see how to package rendering a stock into an individual, reusable component, and how to work with Angular event and data binding. Starting Your First Angular Project As mentioned in the previous chapter, we will heavily rely on the Angular CLI to help us bootstrap and develop our application. I will assume that you have already fol‐ lowed the initial setup instructions in the previous chapter and have Node.js, Type‐ Script, and the Angular CLI installed in your development environment. Creating a new application is as simple as running the following command: ng new stock-market When you run this command, it will automatically generate a skeleton application under the folder stock-market with a bunch of files, and install all the necessary dependencies for the Angular application to work. This might take a while, but even‐ tually, you should see the following line in your terminal: Project 'stock-market' successfully created. 7
  • 29. Congratulations, you have just created your first Angular application! While we created our first application with the vanilla Angular CLI command, the ng new command takes a few arguments that allow you to customize the application generated to your preference. These include: • Whether you want to use vanilla CSS or SCSS or any other CSS framework (for example, ng new --style=scss) • Whether you want to generate a routing module (for example, ng new --routing); we’ll discuss this further in Chapter 11. • Whether you want inline styles/templates • Whether you want a common prefix to all components (for example, to prefix acme to all components, ng new --prefix=acme) And much more. It’s worth exploring these options by running ng help once you are a bit more familiar with the Angular framework to decide if you have specific preferences one way or the other. Understanding the Angular CLI While we have just created our first Angular application, the Angular CLI does a bit more than just the initial skeleton creation. In fact, it is useful throughout the devel‐ opment process for a variety of tasks, including: • Bootstrapping your application • Serving the application • Running the tests (both unit and end-to-end) • Creating a build for distribution • Generating new components, services, routes and more for your application Each of these corresponds to one or more Angular CLI commands, and we will cover each one as and when we need or encounter them, instead of trying to cover each command and its uses upfront. Each command provides further flexibility with a variety of arguments and options, making the Angular CLI truly diverse and capable for a wide variety of uses. 8 | Chapter 2: Hello Angular
  • 30. Running the Application Now that we have generated our application, the next part is to run it so that we can see our live running application in the browser. There are technically two ways to run it: • Running it in development mode, where the Angular CLI compiles the changes as it happens and refreshes our UI • Running it in production mode, with an optimal compiled build, served via static files For now, we will run it in development mode, which is as simple as running ng serve from the root folder of the generated project, which is the stock-market folder in this case. After a little bit of processing and compilation, you should see something like the following in your terminal: ** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** Date: 2018-03-26T10:09:18.869Z Hash: 0b730a52f97909e2d43a Time: 11086ms chunk {inline} inline.bundle.js (inline) 3.85 kB [entry] [rendered] chunk {main} main.bundle.js (main) 17.9 kB [initial] [rendered] chunk {polyfills} polyfills.bundle.js (polyfills) 549 kB [initial] [rendered] chunk {styles} styles.bundle.js (styles) 41.5 kB [initial] [rendered] chunk {vendor} vendor.bundle.js (vendor) 7.42 MB [initial] [rendered] webpack: Compiled successfully. The preceding output is a snapshot of all the files that the Angular CLI generates in order for your Angular application to be served successfully. It includes the main.bundle.js, which is the transpiled code that is specific to your application, and the vendor.bundle.js, which includes all the third-party libraries and frameworks you depend on (including Angular). styles.bundle.js is a compilation of all the CSS styles that are needed for your application, while polyfills.bundle.js includes all the polyfills needed for supporting some capabilities in older browsers (like advanced ECMA‐ Script features not yet available in all browsers). Finally, inline.bundle.js is a tiny file with webpack utilities and loaders that is needed for bootstrapping the application. ng serve starts a local development server on port 4200 for you to hit from your browser. Opening http://localhost:4200 in your browser should result in you seeing the live running Angular application, which should look like Figure 2-1. Understanding the Angular CLI | 9
  • 31. Figure 2-1. Hello Angular application in the browser You can actually leave the ng serve command running in the ter‐ minal, and continue making changes. If you have the application opened in your browser, it will automatically refresh each time you save your changes. This makes the development quick and itera‐ tive. 10 | Chapter 2: Hello Angular
  • 32. In the following section, we will go into a bit more detail about what exactly hap‐ pened under the covers to see how the generated Angular application works and what the various pieces are. Basics of an Angular Application At its core, any Angular application is still a Single-Page Application (SPA), and thus its loading is triggered by a main request to the server. When we open any URL in our browser, the very first request is made to our server (which is running within ng serve in this case). This initial request is satisfied by an HTML page, which then loads the necessary JavaScript files to load both Angular as well as our application code and templates. One thing to note is that although we develop our Angular application in TypeScript, the web application works with transpiled JavaScript. The ng serve command is responsible for translating our TypeScript code into JavaScript for the browser to load. If we look at the structure the Angular CLI has generated, it is something like this: stock-market +----e2e +----src +----app +----app.component.css +----app.component.html +----app.component.spec.ts +----app.component.ts +----app.module.ts +----assets +----environments +----index.html +----main.ts +----.angular-cli.json Root component Main module Root HTML Entry point Angular CLI config There are a few more files than listed here in the stock-market folder, but these are the major ones we are going to focus on in this chapter. In addition, there are unit tests, Basics of an Angular Application | 11
  • 33. end-to-end (e2e) tests, the assets that support our application, configuration specific to various environments (dev, prod, etc.), and other general configuration that we will touch upon in Chapters 5, 10, and 12. Root HTML—index.html If you take a look at the index.html file, which is in the src folder, you will notice that it looks very clean and pristine, with no references to any scripts or dependencies: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>StockMarket</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> </head> <body> <app-root></app-root> </body> </html> Root component for our Angular application The only thing of note in the preceding code is the <app-root> element in the HTML, which is the marker for loading our application code. What about the part that loads the core Angular scripts and our application code? That is inserted dynamically at runtime by the ng serve command, which combines all the vendor libraries, our application code, the styles, and inline templates each into individual bundles and injects them into index.html to be loaded as soon as the page renders in our browser. The Entry Point—main.ts The second important part of our bootstrapping piece is the main.ts file. The index.html file is responsible for deciding which files are to be loaded. The main.ts file, on the other hand, identifies which Angular module (which we will talk a bit more about in the following section) is to be loaded when the application starts. It can also change application-level configuration (like turning off framework-level asserts and verifications using the enableProdMode() flag), which we will cover in Chap‐ ter 12: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; 12 | Chapter 2: Hello Angular
  • 34. import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.log(err)); Bootstrap the main AppModule Most of the code in the main.ts file is generic, and you will rarely have to touch or change this entry point file. Its main aim is to point the Angular framework at the core module of your application and let it trigger the rest of your application source code from that point. Main Module—app.module.ts This is where your application-specific source code starts from. The application mod‐ ule file can be thought of as the core configuration of your application, from loading all the relevant and necessary dependencies, declaring which components will be used within your application, to marking which is the main entry point component of your application: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } NgModule TypeScript annotation to mark this class definition as an Angular module Declarations marking out which components and directives can be used within the application Basics of an Angular Application | 13
  • 35. Importing other modules that provide functionality needed in the application The entry point component for starting the application This is our first time dealing with a TypeScript-specific feature, which are decorators (you can think of them as annotations). Dec‐ orators allow us to decorate classes with annotations and properties as well as meta-functionality. Angular heavily leverages this TypeScript feature across the board, such as using decorators for modules, components, and more. You can read more about TypeScript decorators in the official doc‐ umentation. We will go over the details of each of these sections in the following chapters, but at its core: declarations The declarations block defines all the components that are allowed to be used in the scope of the HTML within this module. Any component that you create must be declared before it can be used. imports You will not create each and every functionality used in the application, and the imports array allows you to import other Angular application and library mod‐ ules and thus leverage the components, services, and other capabilities that have already been created in those modules. bootstrap The bootstrap array defines the component that acts as the entry point to your application. If the main component is not added here, your application will not kick-start, as Angular will not know what elements to look for in your index.html. You usually end up needing (if you are not using the CLI for any reason!) to modify this file if and only if you add new components, services, or add/integrate with new libraries and modules. Root Component—AppComponent We finally get to the actual Angular code that drives the functionality of the applica‐ tion, and in this case, it is the main (and only) component we have, the AppCompo nent. The code for it looks something like this: 14 | Chapter 2: Hello Angular
  • 36. import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; } The DOM selector that gets translated into an instance of this component The HTML template backing this component—in this case, the URL to it Any component-specific styling, again pointing to a separate file in this case The component class with its own members and functions A component in Angular is nothing but a TypeScript class, decorated with some attributes and metadata. The class encapsulates all the data and functionality of the component, while the decorator specifies how it translates into the HTML. The app-selector is a CSS selector that identifies how Angular finds this particular component in any HTML page. While we generally use element selectors (app-root in the preceding example, which translates to looking for <app-root> elements in the HTML), they can be any CSS selector, from a CSS class to an attribute as well. The templateUrl is the path to the HTML used to render this component. We can also use inline templates instead of specifying a templateUrl like we have done in the example. In this particular case, the template we are referring to is app.compo‐ nent.html. styleUrls is the styling counterpart to the template, encapsulating all the styles for this component. Angular ensures that the styles are encapsulated, so you don’t have to worry about your CSS classes from one component affecting another. Unlike tem plateUrl, styleUrls is an array. The component class itself finally encapsulates all the functionality backing your component. It makes it easy to think of the responsibilities of the component class as twofold: • Load and hold all the data necessary for rendering the component • Handle and process any events that may arise from any element in the component Basics of an Angular Application | 15
  • 37. The data in the class will drive what can be displayed as part of the component. So let’s take a look at what the template for this component looks like: <h1> {{title}} </h1> Data-bound title from the component Our HTML is as simple as can be for the component. All it has is one element, which is data-bound to a field in our component class. The double-curly ({{ }}) syntax is an indication to Angular to replace the value between the braces with the value of the variable from the corresponding class. In this case, once the application loads, and the component is rendered, the {{title}} will be replaced with the text app works!. We will talk in more detail about data binding in “Understanding Data Binding” on page 19. Creating a Component So far, we have dealt with the basic skeleton code that the Angular CLI has generated for us. Let’s now look at adding new components, and what that entails. We will use the Angular CLI to generate a new component, but look underneath the covers to see what steps it takes. We will then walk through some very basic common tasks we try to accomplish with components. Steps in Creating New Components Using the Angular CLI, creating a new component is simply running a simple com‐ mand. We will first try creating a stock widget, which displays the name of the stock, its stock code, the current price, and whether it has changed for the positive or nega‐ tive. We can simply create a new stock-item by running the following command from the main folder of the application: ng generate component stock/stock-item There are a few interesting things to note here: • The Angular CLI has a command called generate, which can be used to generate components (like we did in the preceding example), and also to generate other Angular elements, such as interfaces, services, modules, and more. • With the target type, we also specify the name (and the folder) within which the component has to be generated. Here, we are telling the Angular CLI to generate 16 | Chapter 2: Hello Angular
  • 38. a component called stock-item within a folder called stock. If we don’t specify stock, it will create a component called stock-item in the app folder itself. The command will generate all the relevant files for a new component, including: • The component definition (named stock-item.component.ts) • The corresponding template definition (named stock-item.component.html) • The styles for the component (in a file named stock-item.component.css) • The skeleton unit tests for the component (named stock-item.component.spec.ts) In addition, it updated the original app module that we saw earlier so that our Angu‐ lar application recognizes the new module. This is the recommended convention to follow whenever you are working with components: • The filename starts with the name of the item you are creating • This is followed by the type of element it is (in this case, a component) • Finally, we have the relevant extension This allows us to both group and easily identify relevant and related files in a simple manner. When you run the command, you should see something like this: create src/app/stock/stock-item/stock-item.component.css create src/app/stock/stock-item/stock-item.component.html create src/app/stock/stock-item/stock-item.component.spec.ts create src/app/stock/stock-item/stock-item.component.ts update src/app/app.module.ts The source for the component, HTML, and the CSS remain pretty much barebones, so I won’t repeat that here. What is important is how this new component that we create is hooked up and made available to our Angular application. Let’s take a look at the modified app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { StockItemComponent } from './stock/stock-item/stock-item.component'; @NgModule({ declarations: [ AppComponent, StockItemComponent ], Creating a Component | 17
  • 39. imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Importing the newly created stock-item component Adding the new component to the declarations section In the application module, we have to ensure that the new component is imported and added to the declarations array, before we can start using it in our Angular application. Using Our New Component Now that we have created a new component, let’s see how we can use it in our appli‐ cation. We will now try to use this skeleton in the app component. First, take a look at the generated stock-item.component.ts file: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { constructor() { } ngOnInit() { } } The selector for using this component. Note it is prefixed with app, which is added by the Angular CLI by default unless otherwise specified. The component has no data and does not provide any functionality at this point; it simply renders the template associated with it. The template at this point is also triv‐ ial, and just prints out a static message. To use this component in our application, we can simply create an element that matches the selector defined anywhere inside our main app component. If we had more components and a deeper hierarchy of components, we could choose to use it in any of their templates as well. So let’s replace most of the placeholder content in 18 | Chapter 2: Hello Angular
  • 40. app.component.html with the following, so that we can render the stock-item component: <div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <app-stock-item></app-stock-item> </div> Adding our stock-item component All it takes is adding the <app-stock-item></app-stock-item> to our app.compo‐ nent.html file to use our component. We simply create an element using the selector we defined in our component. Then when the application loads, Angular recognizes that the element refers to a component, and triggers the relevant code path. When you run this (or if your ng serve is still running), you should see both the original "app works" along with a new "stock-item works" in the UI. Understanding Data Binding Next, let’s focus on getting some data and figuring out how to display it as part of our component. What we are trying to build is a stock widget, which will take some stock information, and render it accordingly. Let’s assume that we have a stock for a company named Test Stock Company, with a stock code of TSC. Its current price is $85, while the previous price it traded at was $80. In the widget, we want to show both the name and its code, as well as the current price, the percentage change since last time, and highlight the price and percentage change in green if it is an increment, or red if it is a decrement. Let’s walk through this step by step. First, we will make sure we can display the name and code in the widget (we will hardcode the information for now, and we will build up the example to get the data from a different source later). We would change our component code (the stock-item.component.ts file) as follows: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; Creating a Component | 19
  • 41. public price: number; public previousPrice: number; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; } } Implement OnInit interface from Angular, which gives us a hook to when the component is initialized Definition of the various fields we will want to access from the HTML OnInit function that is triggered when a component is initialized Initializing the values for each of the fields Angular gives us hooks into the lifecycle of a component to let us take certain actions when a component is initialized, when its view is rendered, when it is destroyed, and so on. We’ve extended our trivial component with a few notable things: OnInit Angular’s OnInit hook is executed after the component is created by the Angular framework, after all the data fields are initialized. It is generally recommended to do any initialization work of a component in the OnInit hook, so that it makes it easier to test the functionality of the rest of the component without necessarily triggering the initialization flow every time. We will cover the remaining lifecycle hooks in Chapter 4. ngOnInit When you want to hook on the initialization phase of a component, you need to implement the OnInit interface (as in the example) and then implement the ngOnInit function in the component, which is where you write your initializa‐ tion logic. We have initialized the basic information we need to render our stock widget in the ngOnInit function. Class member variables We have declared a few public variables as class instance variables. This informa‐ tion will be used to render our template. Now, let’s change the template (the stock-item.component.html file) to start rendering this information: 20 | Chapter 2: Hello Angular
  • 42. <div class="stock-container"> <div class="name"><h3>{{name}}</h3> - <h4>({{code}})</h4></div> <div class="price">$ {{price}}</div> </div> and its corresponding CSS (the stock-item.component.css file), to make it look nice: .stock-container { border: 1px solid black; border-radius: 5px; display: inline-block; padding: 10px; } .stock-container .name h3, .stock-container .name h4 { display: inline-block; } Note that the CSS is purely from a visual perspective, and is not needed nor impacts our Angular application. You could skip it completely and still have a functional application. Once we make these changes and refresh our application, we should see something like Figure 2-2 in our browser. Figure 2-2. Angular app with stock component We have just used one fundamental building block from Angular to render our data from our component into the HTML. We use the double-curly notation ({{ }}), which is also known as interpolation. Interpolation evaluates the expression between the curly braces as per the component backing it, and then renders the result as a Creating a Component | 21
  • 43. string in place in the HTML. In this case, we render the name, code, and the price of the stock using interpolation. This picks up the values of name, code, and price, and then replaces the double-curly expression with its value, thus rendering our UI. This is Angular’s one-way data binding at work. One-way data binding simply refers to Angular’s capability to automatically update the UI based on values in the compo‐ nent, and then keeping it updated as the value changes in the component. Without one-way binding, we would have to write code to take the value from our component, find the right element in HTML, and update its value. Then we would have to write listeners/watchers to keep track of when the value in the component changes, and then change the value in the HTML at that time. We can get rid of all of this extra code because of data binding. In this particular case, we are binding to simple variables, but it is not necessarily restricted to simple variables. The expressions can be slightly more complex. For example, we could render the same UI by changing the binding expression as follows in stock-item.component.html: <div class="stock-container"> <div class="name">{{name + ' (' + code + ')'}}</div> <div class="price">$ {{price}}</div> </div> In this case, we replaced our multiple heading elements with a single div. The interpo‐ lation expression is now a combination of both the name and the code, with the code surrounded by parentheses. Angular will evaluate this like normal JavaScript, and return the value of it as a string to our UI. Understanding Property Binding So far, we used interpolation to get data from our component code to the HTML. But Angular also provides a way to bind not just text, but also DOM element properties. This allows us to modify the content and the behavior of the HTML that is rendered in the browser. For example, let’s try to modify our stock widget to highlight the price in red if the price is less than the previous price, and in green if it is equal to or more than the previous price. We can first change our component (the stock-item.component.ts) to precalculate if the difference is positive or negative like so: 22 | Chapter 2: Hello Angular
  • 44. import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; public price: number; public previousPrice: number; public positiveChange: boolean; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; this.positiveChange = this.price >= this.previousPrice; } } In this code, we added a new public variable called positiveChange, which is of type boolean, and then set the value based on comparing the current price with the previ‐ ous price. This gives us a singular boolean value that we can use to decide whether to highlight the price in red or green. Next, let’s add some classes in the stock-item.component.css file to allow for changing the color of the text: .stock-container { border: 1px solid black; border-radius: 5px; display: inline-block; padding: 10px; } .positive { color: green; } .negative { color: red; } We simply added two classes, positive and negative, which change the color of the text to green and red, respectively. Now let’s tie this together to see how we can use this information and classes in our stock-item.component.html file: Creating a Component | 23
  • 45. <div class="stock-container"> <div class="name">{{name + ' (' + code + ')'}}</div> <div class="price" [class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div> </div> We have added one new binding on the price div element, which reads as: [class]="positiveChange ? 'positive' : 'negative'" This is the Angular syntax for property binding, which binds the value of the expres‐ sion to the DOM property between the square brackets. The [] is the general syntax that can be used with any property on an element to bind one-way from the compo‐ nent to the UI. In this particular case, we are telling Angular to bind to the class property of the DOM element to the value of the expression. Angular will evaluate it like a normal JavaScript expression, and assign the value (positive in this case) to the class property of the div element. When you bind to the class property like we did in the example, note that it overrides the existing value of the property. In our example, the "price" class is replaced with the class "positive", instead of appending to the existing value of the property. You can notice this for yourself if you inspect the rendered HTML in the browser. Be careful about this if you bind directly to the class property. If the value of the variable positiveChange in the component changes, Angular will automatically re-evaluate the expression in the HTML and update it accordingly. Try changing the price so that there is a negative change and then refresh the UI to make sure it works. Notice that we have been explicitly referring to the data binding working with DOM properties, and not HTML attributes. The following sidebar goes into more detail on the difference between the two, and why it is important to know and understand as you work on Angular. But simplifying it, Angular data binding only works with DOM properties, and not with HTML attributes. HTML Attribute Versus DOM Property: What’s the Difference? As mentioned, when we work with data binding in Angular, we aren’t working with HTML attributes but rather DOM properties. Attributes are defined by HTML, while properties are defined by the Document Object Model. Though some attributes (like ID and class) directly map to DOM properties, others may exist on one side but not the other. 24 | Chapter 2: Hello Angular
  • 46. But more importantly, the distinction between the two is that HTML attributes are generally used for initialization of a DOM element, but after that, they have no pur‐ pose or effect on the underlying element. Once the element is initialized, its behavior is controlled by the DOM properties from then on. For example, consider the input HTML element. If we bootstrap our HTML with something like: <input type="text" value="foo"/> this initializes an input DOM element, with the initial value of the DOM property value to be set to foo. Now let’s assume we type something in the text box, say bar. At this point: • If we do input.getAttribute('value'), it would return foo, which was the attribute value we used to initialize the HTML. • If we do input.value, we will get the current value of the DOM property, which is bar. That is, the attribute value is used to boostrap and set the initial value of the HTML DOM element, but after that, it is the DOM property that drives the behavior. If you inspect the HTML, you will see that it is still the initial HTML we provided, and does not update either. In Angular, we thus bind to the DOM property, and not to the HTML attributes. Whenever we think about one-way binding from the component to the UI, we should always keep this in mind! Just like we did for the class property, depending on the use case, we can actually bind to other HTML properties like the src property of an img tag, or the disabled property of input and button. We will cover this in more depth in the next chapter. We will also cover a simpler and more specific way of binding CSS classes in the next chapter as well. Understanding Event Binding So far, we have worked on using the data in our component to both render values and change the look and feel of our component. In this section, we will start understand‐ ing how to handle user interactions, and work with events and event binding in Angular. Say we wanted to have a button that allows users to add the stock to their list of favor‐ ite stocks. Generally, with a button like this, when the user clicks it, we would want to make some server call and then process the result. So far, since we are working with Creating a Component | 25
  • 47. very simple examples, let’s just say we wanted to handle this click and get a hook to it in our component. Let’s see how we might accomplish that. First, we can change our component code in stock-item.component.ts to add a func‐ tion toggleFavorite, which should be triggered each time the click happens from the UI: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-stock-item', templateUrl: './stock-item.component.html', styleUrls: ['./stock-item.component.css'] }) export class StockItemComponent implements OnInit { public name: string; public code: string; public price: number; public previousPrice: number; public positiveChange: boolean; public favorite: boolean; constructor() { } ngOnInit() { this.name = 'Test Stock Company'; this.code = 'TSC'; this.price = 85; this.previousPrice = 80; this.positiveChange = this.price >= this.previousPrice; this.favorite = false; } toggleFavorite() { console.log('We are toggling the favorite state for this stock'); this.favorite = !this.favorite; } } We have added a new public boolean member variable called favorite, which is ini‐ tialized with a false value. We then added a new function called toggleFavorite(), which simply flips the boolean value of favorite. We are also printing a log in the console to ensure this is getting triggered. Now, let’s update the UI to use this concept of a favorite and also allow users to tog‐ gle the state: 26 | Chapter 2: Hello Angular
  • 48. <div class="stock-container"> <div class="name">{{name + ' (' + code + ')'}}</div> <div class="price" [class]="positiveChange ? 'positive' : 'negative'">$ {{price}}</div> <button (click)="toggleFavorite()" [disabled]="favorite">Add to Favorite</button> </div> We have added a new button in the stock-item.component.html file to allow users to click and add the stock to their favorite set. We are using the data-binding concept from the previous section on the disabled property. Thus, we are disabling the but‐ ton based on the boolean value favorite. If favorite is true, the button will be dis‐ abled, and if it is false, the button will be enabled. Thus, by default, the button is enabled. The other major thing we have on the element is this fragment: (click)="toggleFavorite()" This syntax is called event binding in Angular. The left part of the equals symbol refers to the event we are binding to. In this case, it is the click event. Just like how the square-bracket notation refers to data flowing from the component to the UI, the parentheses notation refers to events. And the name between the parentheses is the name of the event we care about. In this case, we are telling Angular that we are interested in the click event on this element. The right part of the equals symbol then refers to the template statement that Angular should execute whenever the event is triggered. In this case, we want it to execute the new function we created, toggleFavorite. When we run this application in our browser, we can see the new button. Clicking it would render something like Figure 2-3. Notice the other interesting thing, which is Angular data binding at play. When we click the button, our toggleFavorite function is executed. This flips the value of favorite from false to true. This in turn triggers the other Angular binding, which is the disabled property of the button, thus disabling the button after the first click. We don’t have to do anything extra to get these benefits, which is the beauty of data binding. Creating a Component | 27
  • 49. Discovering Diverse Content Through Random Scribd Documents
  • 50. Academy of Sciences was preparing a list of illustrious contemporary scientists to be submitted to the Kaiser with a view to conferring on them the badge of the Order of Merit. As Pasteur’s protest and return of his diploma to the Bonn University had not been forgotten, the Berlin Academy, before placing his name on the list, desired to know whether he would accept this distinction at the hands of the German Emperor. Pasteur, while acknowledging with courteous thanks the honour done to him as a scientist, declared that he could not accept it. For him, as for Victor Hugo, the question of Alsace-Lorraine was a question of humanity; the right of peoples to dispose of themselves was in question. And by a bitter irony of Fate, France, which had proclaimed this principle all over Europe, saw Alsace tom away from her. And by whom? by the very nation whom she had looked upon as the most idealistic, with whom she had desired an alliance in a noble hope of pacific civilization, a hope shared by Humboldt, the great German scientist. It was obvious to those who came near Pasteur that, in spite of the regret caused in him by the decrease of his physical strength, his moral energy remained unimpaired. He never complained of the state of his health, and usually avoided speaking of himself. A little tent had been put up for him in the new garden of the Pasteur Institute, under the young chestnuts, the flowers of which were now beginning to fall, and he often spent his afternoons there. One or other of those who had watched over him through the long winter nights frequently came to talk with him, and he would inquire, with all his old interest, into every detail of the work going on. His old friend Chappuis, now Honorary Rector of the Academy of Dijon, often came to sit with him under this tent. Their friendship remained unchanged though it had lasted more than fifty years. Their conversation now took a yet more exalted turn than in the days of their youth and middle age. The dignity of Chappuis’ life was almost austere, though tempered by a smiling philosophy. Pasteur, less preoccupied than Chappuis by philosophical discussions, soared without an effort into the domain of spiritual things. Absolute faith in God and in Eternity, and a conviction that the power for good given to us in this world will be continued beyond it, were feelings which pervaded his whole life; the virtues of the Gospel had ever been present to him. Full of
  • 51. respect for the form of religion which had been that of his forefathers, he came to it simply and naturally for spiritual help in these last weeks of his life. On June 13, he came, for the last time, down the steps of the Pasteur Institute, and entered the carriage which was to take him to Villeneuve l’Etang. Every one spoke to him of this stay as if it were sure to bring him back to health. Did he believe it? Did he try, in his tenderness for those around him, to share their hopes? His face almost bore the same expression as when he used to go to Villeneuve l’Etang to continue his studies. When the carriage passed through Saint Cloud, some of the inhabitants, who had seen him pass in former years, saluted him with a mixture of emotion and respectful interest. At Villeneuve l’Etang, the old stables of the Cent Gardes had reverted to their former purpose and were used for the preparation of the diphtheria antitoxin. There were about one hundred horses there; old chargers, sold by the military authorities as unfit for further work; racehorses thus ending their days; a few, presents from their owners, such as Marshal Canrobert’s old horse. Pasteur spent those summer weeks in his room or under the trees on the lawns of the Park. A few horses had been put out to grass, the stables being quite full, and occasionally came near, looking over their hurdles towards him. Pasteur felt a deep thankfulness in watching the busy comings and goings of Dr. Roux and his curator, M. Martin, and of the veterinary surgeon, M. Prévôt, who was entrusted with the bleeding operations and the distribution of the flasks of serum. He thought of all that would survive him and felt that his weakened hand might now drop the torch which had set so many others alight. And, more than resigned, he sat peacefully under a beautiful group of pines and purple beeches, listening to the readings of Mme. Pasteur and of his daughter. They smiled on him with that valiant smile which women know how to keep through deepest anguish. Biographies interested him as of yore. There was at that time a renewal of interest in memories of the First Empire; old letters, memoirs, war anecdotes were being published every day. Pasteur never tired of those great souvenirs. Many of those stories brought him back to the emotions of his youth, but he no longer looked with the same eyes on the glory of conquerors. The true guides of humanity now seemed to him to be those
  • 52. who gave devoted service, not those who ruled by might. After enjoying pages full of the thrill of battlefields, Pasteur admired the life of a great and good man, St. Vincent de Paul. He loved this son of poor peasants, proud to own his humble birth before a vainglorious society; this tutor of a future cardinal, who desired to become the chaplain of some unhappy convicts; this priest, who founded the work of the Enfants Trouvés, and who established lay and religious alliance over the vast domain of charity. Pasteur himself exerted a great and charitable influence. The unknown lady who had put at his disposal four scholarships for young men without means came to him in August and offered him the funds for a Pasteur Hospital, the natural outcome, she said, of the Pastorian discoveries. Pasteur’s strength diminished day by day, he now could hardly walk. When he was seated in the Park, his grandchildren around him suggested young rose trees climbing around the trunk of a dying oak. The paralysis was increasing, and speech was becoming more and more difficult. The eyes alone remained bright and clear; Pasteur was witnessing the ruin of what in him was perishable. How willingly they would have given a moment of their lives to prolong his, those thousands of human beings whose existence had been saved by his methods: sick children, women in lying-in hospitals, patients operated upon in surgical wards, victims of rabid dogs saved from hydrophobia, and so many others protected against the infinitesimally small! But, whilst visions of those living beings passed through the minds of his family, it seemed as if Pasteur already saw those dead ones who, like him, had preserved absolute faith in the Future Life. The last week in September he was no longer strong enough to leave his bed, his weakness was extreme. On September 27, as he was offered a cup of milk: “I cannot,” he murmured; his eyes looked around him with an unspeakable expression of resignation, love and farewell. His head fell back on the pillows, and he slept; but, after this delusive rest, suddenly came the gaspings of agony. For twenty-four hours he remained motionless, his eyes closed, his body almost entirely paralyzed; one of his hands rested in that of Mme. Pasteur, the other held a crucifix. Thus, surrounded by his family and disciples, in this room of almost monastic simplicity, on Saturday, September 28, 1895, at 4.40 in the afternoon, very peacefully, he passed away.
  • 54. INDEX A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, Y, Z
  • 55. A Abbadie, d’, presents medals to Pasteur, 449 Abdul Aziz, Sultan, 141 About, Edmond: On Pasteur, 383 On Pasteur’s lecture at Sorbonne, 122 Pamphlet quoted, 177 Académie des Sciences, 29 note, 81 During siege of Paris, 186 Académie Française, Pasteur’s reception at, 345 Aërobes, 99 Agrégation, 31 note Alais: Pasteur goes to, 115, 117, 129, 138, 155, 166 Statue to J. B. Dumas at, 446 Alexandria, French mission to, 377 Alfort, experiments on sheep at, 306 Alsace-Lorraine question, 461 Amat, Mlle., 170 Anaërobes, 99, 220 Andral, Dr., 160 Advice to Pasteur, 247 Anglada, work “On Contagion” quoted, 80 Anguillulæ, 150 Anthrax (splenic fever, charbon), 257 seqq., 292 Hens and, 267, 277 Commission on, 278 Vaccination against, 311, 312 Experiment, 315, 317, 318, 320, 328, 367, 368 Results, 325, 367, 368 Antirabic inoculation on man, 414 Discussion on, 434 Anti-vivisection, Virchow on, 332 Aosta, Duke and Duchess of, 141 Arago, 27, 356 On Monge, 195 Speech before Chamber of Deputies, 245
  • 56. Arbois: Pasteur at, 6, 7, 180, 420, 437 Presentation to Pasteur from, 449 Prussians at, 202 Arboisian characteristics, 8 Arcis-sur-Aube, battle of, 4 Ardèche, 32 Ardouin, Dr., 380 Aristotle, allusions to hydrophobia, 407 Arsonval, M. d’, 280 Aselli, discoveries through vivisection, 336 Aspartic acid, 57, 70 Aspergillus niger, 204 Aubenas, tribute to Pasteur, 350, 351 Augier, Emile, 174 Aurillac, testimonial to Pasteur, 373 B “Baccalauréat,” 10 and note Baciocchi, Princess, leaves Villa Vicentina to Prince Imperial, 173 Bagnères-de-Luchon, 104 Balard, lecturer at Ecole Normale, 29, 31, 56, 59, 100, 106 Advice to Pasteur, 217 Appeal to Pasteur, 217 Discovers bromin, 32 Inspector-General of Higher Education, 145 On Pasteur’s discovery, 40 Bar-sur-Aube, 3rd Regiment at, 3 Barbet Boarding School, 10, 12, 21 Barbet, M., 10, 22 Barbier, Captain, 10 Barrnel, Dumas’ Curator, 25 Bastian, Dr., attacks Pasteur, 253 seqq. Baudry, Paul, 127 Bazaine at Metz, 186 Beauce, 147 note Splenic fever in, 257, 276, 284, 314
  • 57. Béchamp, theory of fermentation, 241 Béclard, Permanent Secretary of Académie de Médecine, 309 On Commission on hydrophobia, 395 Beer, Pasteur studies manufacture of, 207 seqq. Béhier, Dr., 233 Behring discovers antitoxin for diphtheria, 455 Bellaguet, M., 137 Belle, Jeanne, wife of Claude Pasteur, 2 Bellevue, Château, Napoleon and William of Prussia meet at, 182 Belotti, M., 206 Berchon, sanitary director, Bordeaux, 340 Bergeron, Jules: Annual Secretary of Académie de Médecine, 309 On Pasteur’s treatment of hydrophobia, 424 Speech at Pasteur Jubilee, 449 Bernard, Claude, 42 At Académie de Médecine, 225 At Tuileries, 154 Discoveries, 135 Experiment on dog, 335 Experiments on fermentation, 280 Illness, 134 Joins in Pasteur’s experiments, 104 Letter to Deville, 137 Letter to Pasteur, 136 On fermentation, 80 — Medicine, 226 — Pasteur’s researches, 72, 87 — Primary causes, 244 — Vivisection, 336 Posthumous notes, 280, 287 Senator, 174 Studies cholera, 126 Bersot, Ernest, quoted on spontaneous generation, 92 Bert, Paul, 279, 374 Classifies Pasteur’s work, 375 Experiments, 263, 392
  • 58. On Commission on hydrophobia, 395 Speech on Pasteur’s discoveries, 245, 246 Berthelot, M.: Consulted by Pasteur, 439 On alcoholic fermentation, 286 Berthollet, M., 248, 356 Discoveries, 195 Bertillon, candidate for Académie de Médecine, 225 Bertin, M., 354 At Ecole Normale, 19, 145, 161, 180, 188 Character, 45, 145 Professor of Physics, Strasburg, 45 Welcomes Pasteur to Paris, 212 Bertrand, Joseph: Letters to Pasteur, 138 Sketch of, 419 Speech at inauguration of Pasteur Institute, 441 Speech at Pasteur Jubilee, 449 Berzelius, 195 Studies paratartaric acid, 25 Theories of fermentation, 80, 241 Besançon, Jean Henri Pasteur at, 2, 4 Besson, candidature for Senate, 249 Beust, Baron von, superintendent of factories, 65 Bigo manufactures beetroot alcohol, 79 Biot, J. J., 27, 42, 55, 59, 204 Attitude towards spontaneous generation, 89, 100 Death, 101, 102 Interview with Pasteur, 41 Last letter, 103 Letters to Joseph Pasteur, 57, 58, 71, 81 Letter to Louis Pasteur, 59 Oldest member of Institute, 81 Passion for reading, 89 Praises Pasteur, 55 Biot, M., veterinary surgeon, at Pouilly le Fort experiment, 316, 320 Bischoffsheim, Raphael, lends villa to Pasteur, 433
  • 59. Bismarck, Prince: Armistice with France, 193 Interview with Jules Favre, 184 On Napoleon III, 182 Blondeau, registrar of mortgages, 13 Bollène, Pasteur at, 360 Bonaparte, Elisa, at Villa Vicentina, 173 Bonn, sous-préfecture, 189 University, 189 Bonnat, portrait of Pasteur, 440 Bordeaux, Pasteur at, 338 Bordighera: Earthquake at, 436 Pasteur at, 434 Borrel attends on Pasteur, 459 Bouchardat, M.: On Commission of Hygiene, 186 Report on remedies for hydrophobia, 408 Bouillaud, Dr., 229, 262, 294 Bouillier, M. F., Director of Ecole Normale, 145, 180 Bouley, H., 264, 278, 323, 354 At experiment on earthworms, 304 Chairman of Commission on hydrophobia, 395, 396, 397, 398 Report, 398 Death, 424 Letters to Pasteur, 324, 329 — on Colin, 320 — germ of hydrophobia, 398 — methods of Delafond and Pasteur, 275 — microbes, 365, 367 — Pasteur’s treatment of hydrophobia, 423 — remedies for hydrophobia, 408 — virulence of bacteridia, 311 Sketch of, 262 Statistics of death from hydrophobia, 428 Vaccinates sheep against anthrax, 306 Bourbaki, General:
  • 60. Death, 193 Retreat of Army Corps, 192 Bourboulon, Commandant, gives Pasteur news of his son, 193 Bourgeois, Philibert, 3 Bourrel sends dogs to laboratory, 390, 396 Boussingault, M., 354 Boutet, veterinary surgeon, 261, 283, 329 On splenic fever, 276 Report of vaccinated sheep, 363 Boutroux, curator in Pasteur’s laboratory, 255 Boyle, Robert, on fermentation, 223 Brand, Dr., treatment of typhoid, 364 Breithaupt, Professor of Mineralogy, 65 Bretonneau, on diphtheria, 453 Brie cattle suffer from anthrax, 257, 314 Brochin, candidate for Académie de Médecine, 225 Brongniart, Alexandre, 42 On Commission on spontaneous generation, 106 Brouardel, Professor: On antirabic cure, 434, 437 Speech at Congress of Hygiene, 446 Speech at Pasteur Jubilee, 449 Broussais, surgery under, 235 Bruce, Mrs., presents Pasteur with Life of Livingstone, 389 Buda-Pesth, Hygiene and Demography Congress at, 456 Budberg, M. de, Russian Ambassador, 127 Budin and antisepsis, 290 Buffon, theory of spontaneous generation, 90 Buonanni, recipe for producing worms, 89 Butyric fermentation, 99 C Cagniard-Latour studies yeast, 80, 81 Cailletet invents apparatus for liquefaction of gases, 384 Cairo, cholera at, 377 Calmette, Edouard: At Lille, 461
  • 61. At Pasteur Jubilee, 447 Attends on Pasteur, 459 Cambon, Governor-General of Algeria, letter to Pasteur, 451 Cardaillac, M. de, 163 Cardinal cultivates silkworms, 139 Carnot, President, 248 At inauguration of Pasteur Institute, 440 At Pasteur Jubilee, 448 Caro, deputy to Edinburgh, 384 Casabianca, Comte de, 168, 169 Celsus on hydrophobia, 407, 409 Chaffois, 192, 193 Chaillou collaborates with Roux, 455 Chamalières brewery, 207 Chamberland, M.: At Pasteur Jubilee, 447 Collaborates with Pasteur, 260, 269, 271, 283, 289, 303, 305, 306, 308, 311, 317, 319, 321, 359, 420, 424 Cross of Legion of Honour, 326 On Pasteur’s early researches, 445 Vaccinations against anthrax, 440 Chambéry, Pasteur at, 131 Chamecin, wood merchant, 3 Chamonix, Pasteur at, 97 Chantemesse, Dr.: Attends on Pasteur, 459, 460 On antirabic cure, 434 Performs inoculations, 432 Chanzy, General, open letter, 190 Chappuis, Charles, 33 Letter to Pasteur, 20 On national testimonial to Pasteur, 246 Sketch of, 18 Visits Pasteur, 462 Chaptal, discoveries of, 195 Charbon. (See Anthrax) Charcot on Pasteur’s antirabic cure, 438
  • 62. Charrière, schoolfellow of Louis Pasteur, 7, 37 Charrin, Dr., performs inoculations, 432 Chartres: Experiment on vaccination against anthrax near, 328 Pasteur at, 284, 303 Scientific congress at, 276 Chassaignac, Dr., on “laboratory surgery,” 228 Chauveau on contagion, 366 Chemists and Physicians, 224, 233 Chevreul, M., 59 On siege of Paris, 188, 189 Chicken cholera, 297 seqq. Chiozza, letter to Pasteur, 200 Cholera, 126 At Damietta and Cairo, 378 Christen, town councillor at Vaucresson, 406 Christophle, speech at inauguration of Pasteur Institute, 441 Clermont Ferrand, Pasteur at, 206 Clouet invents system of manufacturing steel, 195 Coblentz, préfecture, 189 Cochin, Denys, at Pasteur Jubilee, 448 Colin, Professor G., 277, 278 Advice to Biot, 319 Experiments on anthrax, 264, 267, 268 Collège de France, 40 note, 146 Compiègne, Pasteur at, 127 Comte, Auguste, 124, 125 Doctrine, 342 Conseil-Général de département, 78 note Contagious diseases, problem of, 223 seqq. Conti, Napoleon III’s secretary, 153 Copenhagen Medical Congress, Pasteur at, 398 Coquelin: Acts in Plaideurs, 128 Recites at Trocadéro fête, 431 Cornil, on acarus of itch, 366 Coulon, schoolfellow of Louis Pasteur, 7, 36
  • 63. Cribier, Mme., 161 Cuisance River, 6, 7, 181 Cuvier, 356 D Daguerre, national testimonial to, 245 Dalimier, Paul, Pasteur’s advice to, 109 Dalloz, editor of Moniteur, 158 Damietta, cholera at, 378 Darboux, “doyen” of Faculty of Science, 31 Daremberg, Dr., on Pasteur at Medical Congress, 332 Darlay as science master, 14 Darwin: On earthworms, 304 On vivisection, 337 Dastre, M., 279 Daubrée, speech at Pasteur Jubilee, 449 Daunas, sketch of, 14 David, Jeanne, wife of Denis Pasteur, 1 Davaine, Dr. C., 272, 278, 354 At experiment on earthworms, 304 Experiments on septicæmia, 229, 265 On butyric ferment, 228, 258 Davy, Sir H., 195 Debray, M., 327 Déclat, Dr., on Pasteur’s experiments, 223 Prescribes carbolic solution for wounds, 239 Delafond, Dr.: On charbon blood, 258 Studies anthrax, 275 Delafosse, Professor of Mineralogy, 33, 36 Delaunay acts in Plaideurs, 128 Delesse, Professor of Science at Besançon, 45 Delort, General Baron, 30 Native of Arbois, 202 Demarquay, Dr., prescribes carbolic solution for wounds, 239
  • 64. Denmark, King and Queen of, at Medical Congress, 399 Denonvilliers, surgery under, 235 Départements, 52 note Descartes in Holland, 200 Despeyroux, Professor of Chemistry, 171 Dessaignes, chemist, 70 Deville, Henri Sainte Claire, 42, 45, 137, 160 Admiration for Pasteur’s precision, 287 At Compiègne, 162 At Tuileries, 154 Character, 146 Congratulates Pasteur on Testimonial, 246 Death, 327 Laboratory, 84 Letter to Mme. Pasteur, 174 On Académie and Science, 196 On Commission of Hygiene, 186 Scientific mission in Germany, 179 Studies cholera, 126 Devise, speech at Pasteur Jubilee, 449 Diabetes, 135 Diderot on spontaneous generation, 90 Didon, gratitude to Pasteur, 144, 161 Dieffenbach, M., 335 Dieulafoy, Professor, attends Pasteur, 459 Diphtheria, 453 Statistics of mortality, 456 Disraeli quoted on public health, 446 Dôle: Jean Joseph Pasteur settles at, 5 Memorial plate on Pasteur’s house at, 376 Presentation to Pasteur from, 450 Douay village, 1 Doucet, Camille, on Pasteur’s speech, 345 Dresden, Pasteur at, 65 Droz, Joseph, his moral doctrine, 16 Dubois, Alphée, engraves medal for Pasteur, 354
  • 65. Dubois, Paul, 127 Bust of Pasteur, 401 Duboué, Dr., theory on hydrophobia, 393 Duc, Viollet le, 127, 128 Du Camp, Maxime, 346 Duchartre elected member of Académie, 100 Duclaux, M., 102, 103, 104, 131, 138, 169, 170, 204, 205 Accompanies Pasteur to Milan, 250 Advice to Pasteur, 217 Annals of Pasteur Institute, 434 At Pasteur Jubilee, 448 Class of biological chemistry, 440 Congratulates Pasteur on testimonial, 246 On Bastian, 253 On heating liquids, 255 Professor of Chemistry at Clermont Ferrand, 206 Ducret, Antoine and Charles, shot, 202 Ducrot, General, 155 Dujardin-Beaumetz, on antirabic cure, 434 Dumas, Alexandre, 106, 107 Pasteur and, 341 Visits Pasteur, 460 Dumas, J. B., 418 Académie sponsor for Pasteur, 344 Advice to Pasteur, 89, 103 Appreciation of Pasteur, 252 At Alais, 170 Death, 384 Interest in sericiculture, 117 La Vie d’un Savant, 383 note; letter on, 383 Laboratory, 42 Letter to Bouley, 312 Letters to Pasteur, 60, 166, 169 On Académie and Science, 196 — Commission on spontaneous generation, 106 — Critical Examination, 287
  • 66. — Destruction of Regnault’s instruments, 191 — Fermentation, 79, 80 Presents Pasteur to Napoleon III, 104 President of Monetary Commission, 145 Requests Pasteur for article on Lavoisier, 121, 122 Senator, 174 Sketch of, 356 Sorbonne lecturer, 21, 25, 40, 44, 55, 59 Speech at Péclet’s tomb, 328 Speech to Pasteur, 354 Statue at Alais to, 446 Dumont, Dr., 8 Dupuy, Charles, speech at Pasteur Jubilee, 448 Duran, Carolus, portrait of Pasteur, 439 Duruy, M., 106 At inauguration of Pasteur Institute, 441 At Tuileries, 154 Attitude towards Germany, 178 Letter to Pasteur, 139 Minister of Public Instruction, 130 System of National Education, 140 Visits Pasteur, 165 E Earthworms, pathogenic action of, 304 Eastern Army Corps, 192, 193 Ecole Normale, 10 and note, 154 An ambulance, 180, 188 Disturbances at, 143 Scientific Annals of, 110 Students enlist, 180 Ecole Polytechnique, 43 note, 154 Edelfeldt, portrait of Pasteur, 440 Eggs, researches on alteration of, 231 Ehrenberg, discoveries on infusories, 214 Electric telegraph, birth of, 76
  • 67. Elsinore, congress visit, 402 Emperor of Brazil, interest in Pasteur’s experiments, 403 Empress Eugénie: At Bordighera, 436 Interview with Pasteur, 127, 128 Regent, 182 Enfants Malades hospital: diphtheritic treatment at, 455 English commission on inoculation for hydrophobia, 430 Report, 437 Erdmann, M., 64 Exhibition reward distribution, 141 F Facultés, 31 note Falloux, attitude towards liberty of teaching, 52 Fauvel, on Pasteur’s inductions, 369 Favé, General, 133, 147, 162, 163 Favre, Jules, Minister of Foreign Affairs, 182 Armistice, 193 Interview with Bismarck, 184 “February days,” 37 note Feltz on puerperal fever, 292 Fermentation, teaching on, 80, 101, 222, 240 Alcoholic, 85, 104, 113, 286 Butyric, 99, 220, 228, 258 Lactic, 83, 215 of tan, 186 Virus, 223 seqq. Ferrières Château, interview between Bismarck and Favre at, 184 Fikentscher, obtains racemic acid, 62 Fleming, Mr., 430 On commission on inoculation for hydrophobia, 430 Flesschutt, Dr., 131 Fleys, Dr., proposes toast of Pasteur, 373 Flourens, on spontaneous generation, 105, 106 Fontainebleau, Napoleon at, 4 Formate of strontian crystals, 50
  • 68. Fortoul, Minister of Public Instruction, 75 Fouqué, M., 327 Fourcroy, M., 248 Discoveries of, 195 Foy, General, works of, 183 Franco-German War, 177 seqq. Franklin on scientific discovery, 76 Frederic III, sketch of, 330 Frémy, M.: On origin of ferments, 216, 218 Theory of fermentation, 241 French character, 207 G Gaidot, Father, 12 Gaillard, M. de, 361 Galen: Discoveries through vivisection, 336 Remedy for hydrophobia, 407 Galtier, experiments on hydrophobia, 393 Garde Nationale, 37 note Gardette, M. de la, 361 Gautier, Théophile, 125 Gay-Lussac, 356 Lectures at Jardin des Plantes, 419 Speech before Chamber of Peers, 245 Studies racemic acid, 26 Gayon, researches on alteration of eggs, 231 Geneva Congress of Hygiene, 357 Germs, Pasteur’s theory of, 187 Gernez, M., 104, 161, 166, 169, 170, 327 Centenary of Ecole Normale, 110 Collaborates with Pasteur, 130, 138, 156, 204 Gérôme, Knight of Legion of Honour, 142 Gille, Dr., attends Pasteur, 459 Girard on vineyard labourers and Pasteur, 420 Girardin, St. Marc, 82
  • 69. Girod, Henry, Royal Notary of Salins, 1 Glénard adopts Brand’s treatment of typhoid, 364 Godélier, Dr., 160 Goltz, M. de, Prussian Ambassador, 127 Gosselin, Dr., 240 Got acts in Plaideurs, 128 Gounod conducts Ave Maria at Trocadéro fête, 431 Grancher, Dr.: Admiration for Pasteur’s experiments, 417, 424 Advises Pasteur to winter in South, 432 Attends Pasteur, 459 On antirabic cure, 434 Pasteur consults, 415 Performs inoculations, 432 Speech at inauguration of Pasteur Institute, 441 Grandeau, M., 327 Letter to Pasteur, 341 Gravière, Admiral Jurien de la, 433 Gréard, deputy to Edinburgh, 384 Greece, King and Queen of, at Medical Congress, 399 Grenet, Pasteur’s curator, 213 Gressier, M., Minister of Agriculture, 275 Grévy, Jules, supports Tamisier and Thurel, 248 Gridaine, Cunin, Minister of Agriculture, 275 Gsell, Stéphane, on origin of Sériana, 452 Guérin, Alphonse, on cause of purulent infection, 236 Guérin, Jules, on vaccine, 308 Guillaume, Eugène, deputy to Edinburgh, 384 Guillemin, M., 77 Schoolfellow of Louis Pasteur, 7 Guizot, M.: Deputy to Edinburgh, 384 Quoted on spontaneous generation, 112 Welcomes Biot to Académie, 82 Guyon, Professor: Accepts Pasteur’s advice, 232 Attends Pasteur, 459
  • 70. H Hankel, Professor of Physics at Leipzig, 64 Hardy, M., welcomes Pasteur to Académie de Médecine, 370 Harvey, discoveries through vivisection, 336 Hautefeuille, M., 327 Heated wine, experiments on, 157 Hemiorganism, 216 Henner, portrait of Pasteur, 439 Henri IV plants mulberry trees, 116, 172 Hens and anthrax, 267, 277 Commission on, 278 Héricourt, Dr., 455 At Villeneuve l’Etang, 445 Hervé, Edouard, 427 Heterogenia. (See Spontaneous generation) Hippocrates, allusions to hydrophobia, 407 Horsley, Victor, secretary to Commission on inoculation for hydrophobia, 431, 437 Houssaye, Henry, on ovation to Pasteur, 426 Hugo, Victor, Année Terrible, 191 Huguenin, portrait of Bonaparte, 181 Humbert of Italy, Prince, 141 Humboldt, Alexander von, interview with J. B. Dumas, 356 Husson, M., 166 Researches on Vaccine, 405 Huxley on Pasteur’s discoveries, 374, 375 Hydrophobia: Dogs inoculated against, 395; Commission, 395, 410 English Commission on inoculation for, 430 Report, 437 Experiments on, 318, 363, 383, 390, 410, 422 seqq. Former remedies, 407 Origin of, 409 Hygiene: Central Commission, 186
  • 71. International Congress of, 446 I Iceland spar, 27 Ingenhousz, 100 Institut de France, 29 note J Jacobsen, J. C., founds Carlsberg Brewery, 401 Jacquinet, sub-director of Ecole Normale, 84, 144, 145 Jaillard, experiments on anthrax, 258, 261 Jamin, M., 354 On heterogenist dispute, 111 Jarry, Claude, royal notary, 2 Jenner, national rewards to, 374 Joinville, Prince de, 53 and note Joly, Nicolas, professor of physiology, Toulouse, 95, 104, 138, 216, 255 Demands Commission on spontaneous generation, 105, 111 Lecture at Faculty of Medicine, 111 Jouassain, Mlle., acts in Plaideurs, 128 Joubert, professor of physics at Collège Rollin, 254, 265, 269, 271 Jourdan, Gabrielle, wife of Jean Henri Pasteur, 2 Journal de la Médecine et de la Chimie quoted, 310 Joux, forest of, 1 Jupille, J. B., bitten by mad dog, 421; inoculated, 422 K Kaempfen, director of fine arts, Dôle, 376 Kestner, produces paratartaric acid, 26, 62, 65, 68 Kitasato, discovers antitoxin for diphtheria, 455 Studies plague, 458 Klebs, discovers bacillus of diphtheria, 454 Klein, Dr., pneumo-enteritis of swine, 362 Koch, Dr.: At Thuillier’s funeral, 381
  • 72. Campaign against Pasteur, 357, 359, 363, 367 Finds bacillus of tuberculosis, 227 On bacillus anthracis, 259, 260 Studies cholera, 379, 382 Kuhn, Chamalières brewer, 207 L Laboratories, 42, 84, 153 Lachadenède, M. de, 121, 171 Lactic fermentation, 83, 99 Lagrange, quoted on Lavoisier’s execution, 195 Lamartine, 36 and note Lambert, Françoise, wife of Claude Etienne Pasteur, 2 Lamy, Auguste, 161 Landouzy, on ambulance ward (1870), 235 Lannelongue, Dr., 289, 391 Laplace, M., 356 Lapparent, M. de, Chairman of Commission on wine, 156, 157 Larrey Baron, 309 On Jupille and Pasteur’s discovery, 423 Surgery under, 235, 240 Laubespin, Comte de, 427 Lauder-Brunton, Dr., on Commission on inoculation for hydrophobia, 430 Laurent, Auguste, 55 Sketch of, 31, 33 Laurent, Madame, 47 Laurent, Maria. (See Pasteur, Mme. Louis) Laurent, M., Rector of Academy of Strasburg, 47, 156 Sketch of, 47, 54 Lavoisier, death, 195 Edition of his works, 122 Le Bel, studies on stereo-chemistry, 445 Le Dantec, studies on yellow fever in Brazil, 461 Le Fort, Léon: On puerperal fever, 290 Surgery under, 235, 270 Le Roux, Dissertation sur la Rage, 407
  • 73. Le Verrier, 129 note, 131 Leblanc, statistics of deaths from hydrophobia, 428 Lechartier, M., 104, 327 Lefebvre, General, 4 Lefort, Mayor of Arbois, 202 Lemaire, Jules, prescribes carbolic solution for wounds, 239 Lemuy, situation of, 1 Leplat, experiments on anthrax, 258, 261 Lereboullet, on anthrax, 269 Lesseps, Ferdinand de, 142 Deputy to Edinburgh, 384 Leval Division: At Arcis-sur-Aube, 4 At Bar-sur-Aube, 3 Lhéritier, candidate for Académie de Médecine, 225 Liberty of teaching, law on, 52 Liebig: Ideas on fermentation, 175, 215, 222 Interview with Pasteur, 176 Theory of fermentation, 80, 81, 241 Lille: Pasteur Dean of Faculté at, 75 Pasteur Institute at, 461 Lister, Sir Joseph: Appreciation of Pasteur, 252 At Pasteur Jubilee, 449 Letter to Pasteur, 238 Method of surgery, 238, 239 On Commission on inoculation for hydrophobia, 430 Surgical method, 187, 216 Littré: Medicine and Physicians, 294 On Microbe, 267 On primary causes, 244 Sketch of, 342 Loeffler, isolates bacillus of diphtheria, 454 Loir, Adrien, 54, 58, 360, 362, 402
  • 74. Dean of Lyons Faculty of Science, 194 Head of Pasteur Institute, Tunis, 461 London, Pasteur visits, 210 London Medical Congress, Pasteur at, 329 London Society for Protection of Animals, complaints on vivisection, 336 Longet, Dr., Treatise on Physiology, 127 Lons-le-Saulnier, 192, 248 Louis XI introduces mulberry tree into Touraine, 116 Louis XVI, 171 Proposal for balloon ascent, 405 Lucas-Championnière, Just: Edits Journal de la Médecine, 310 On dressing of wounds, 238 Lycée St. Louis, 11, 21, 22 Lyons, Pasteur at, 194 Lyons Commission on silkworm disease, 170 M MacDonald, General, 4 Magendie, M.: Experiment with rabic blood, 392 Interview with Quaker, 334 Maillot, M.: Accompanies Pasteur to Milan, 249 Collaborates with Pasteur, 130, 138, 166, 169 Mairet, Bousson de, sketch of, 8 Maisonneuve, Dr., prescribes carbolic solution for wounds, 239 Malic acid, optical study of, 57, 59 Malus, Etienne Louis, discovers polarization of light, 27 Marat, conduct to Lavoisier, 195 Marchoux, attends on Pasteur, 459 Marcou, geologist, 161 Marie, Dr., attends on Pasteur, 459 Marie, Grand Duchess of Russia, 141 Marmier, attends on Pasteur, 459 Marnoz, Jean Joseph, Pasteur at, 6 Martin, M.:
  • 75. Attends on Pasteur, 459 Collaborates with Roux, 455 Lecture on diphtheria, 457 Maternité, mortality at, 290 Mathilde, Princesse, 107 Salon, 125 Maucuer, at Bollène, 360 Maunory, M., 284, 303 Maury, A., 137 Medici, Catherine de, plants mulberry tree in Orléannais, 116 Medicine, general condition (1873), 226, 233 Meissonier, Knight of Legion of Honour, 142 Meister, Joseph, 432 Bitten by mad dog, 414 Inoculated, 415, 429 Melun Agricultural Society, tribute to Pasteur, 350 Melun, experiment on vaccination of anthrax near, 314, 316 Méricourt, Le Roy de, 225 Méry, on anatomists, 226 Mesnil, M. du, 163 Attends on Pasteur, 459 Metchnikoff: At Pasteur Jubilee, 448 Directs private laboratories, 440 Work on “leucocytes,” 458 Metz surrendered, 185 Meudon, proposed laboratory at, 398 Mézières, mission to Edinburgh, 384 Michelet quoted on his friendship with Poinsat, 18 Microbe: Rossignol on, 314 Word invented, 266 Microscope, results of its invention, 90 Mièges, near Nozeroy, registers of, 1 Milan Congress of Sericiculture, Pasteur at, 249 Miller, M., 66 Milne-Edwards:
  • 76. Welcome to Our Bookstore - The Ultimate Destination for Book Lovers Are you passionate about books and eager to explore new worlds of knowledge? At our website, we offer a vast collection of books that cater to every interest and age group. From classic literature to specialized publications, self-help books, and children’s stories, we have it all! Each book is a gateway to new adventures, helping you expand your knowledge and nourish your soul Experience Convenient and Enjoyable Book Shopping Our website is more than just an online bookstore—it’s a bridge connecting readers to the timeless values of culture and wisdom. With a sleek and user-friendly interface and a smart search system, you can find your favorite books quickly and easily. Enjoy special promotions, fast home delivery, and a seamless shopping experience that saves you time and enhances your love for reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookgate.com