You are on page 1of 53

Ang-book 2: The Complete Book on

Angular 2 1st Edition Nate Murray


Visit to download the full and correct content document:
https://textbookfull.com/product/ang-book-2-the-complete-book-on-angular-2-1st-editi
on-nate-murray/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

ng-book The Complete Guide to Angular Nate Murray

https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-nate-murray/

ng-book: The Complete Guide to Angular 5 Nathan Murray

https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-5-nathan-murray/

Ng Book The Complete Guide to Angular 9 Nathan Murray

https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-9-nathan-murray/

Ng Book The Complete Guide to Angular 11 Felipe Coury

https://textbookfull.com/product/ng-book-the-complete-guide-to-
angular-11-felipe-coury/
ng book The Complete Book on AngularJS 1st Edition Ari
Lerner

https://textbookfull.com/product/ng-book-the-complete-book-on-
angularjs-1st-edition-ari-lerner/

Angular 2 Cookbook Frisbie

https://textbookfull.com/product/angular-2-cookbook-frisbie/

Angular 2 ui development Kasagoni

https://textbookfull.com/product/angular-2-ui-development-
kasagoni/

Marquise (Mansion On The Hill Book 2) 1st Edition


Chashiree M. & M.K. Moore [M.

https://textbookfull.com/product/marquise-mansion-on-the-hill-
book-2-1st-edition-chashiree-m-m-k-moore-m/

Kovana Outsider Book 2 1st Edition Aiden Phoenix

https://textbookfull.com/product/kovana-outsider-book-2-1st-
edition-aiden-phoenix/
ng-book 2
Felipe Coury, Ari Lerner, Nate Murray, & Carlos Taborda
© 2015 - 2016 Felipe Coury, Ari Lerner, Nate Murray, & Carlos Taborda
Contents

Book Revision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Prerelease . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Bug Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chat With The Community! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Be notified of updates via Twitter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
We’d love to hear from you! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Writing your First Angular 2 Web Application . . . . . . . . . . . . . . . . . . . . . . . . 1


Simple Reddit Clone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
TypeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Example Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Angular’s Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
All Dependencies Loaded . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Adding CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Our First TypeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Making a Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Adding a template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Booting Our Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Loading our Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Running The App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Compiling the TypeScript Code to .js . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Using npm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Serving The App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Compiling on every change . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Adding Data to the Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Working with arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Expanding our Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
The Application Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Adding Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Adding the Article Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Rendering Multiple Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Creating an Article class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Storing multiple Articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
CONTENTS

Configuring the ArticleComponent with inputs . . . . . . . . . . . . . . . . . . . . . 46


Rendering a List of Articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Adding New Articles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Finishing Touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Displaying the Article Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Re-sorting Based on Score . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Full Code Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

TypeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Angular 2 is built in TypeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
What do we get with TypeScript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Trying it out with a REPL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Built-in types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Fat Arrow Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Template Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Wrapping up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

How Angular Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75


Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
The Navigation Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
The Breadcrumbs Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
The Product List Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Product Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Component Decorator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Component selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Component template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Adding A Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Viewing the Product with Template Binding . . . . . . . . . . . . . . . . . . . . . . . 85
Adding More Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Selecting a Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Listing products using <products-list> . . . . . . . . . . . . . . . . . . . . . . . . . 87
The ProductsList Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Configuring the ProductsList @Component Options . . . . . . . . . . . . . . . . . . . 91
CONTENTS

Component inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Component outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Emitting Custom Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Writing the ProductsList Controller Class . . . . . . . . . . . . . . . . . . . . . . . . 97
Writing the ProductsList View Template . . . . . . . . . . . . . . . . . . . . . . . . 98
The Full ProductsList Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
The ProductRow Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
ProductRow Component Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . 103
ProductRow Component Definition Class . . . . . . . . . . . . . . . . . . . . . . . . . 103
ProductRow template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
ProductRow Full Listing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
The ProductImage Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
The PriceDisplay Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
The ProductDepartment Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
NgModule and Booting the App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Booting the app . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
The Completed Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
A Word on Data Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

Built-in Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111


Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
NgIf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
NgSwitch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
NgStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
NgClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
NgFor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Getting an index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
NgNonBindable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

Forms in Angular 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127


Forms are Crucial, Forms are Complex . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
FormControls and FormGroups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
FormControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
FormGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Our First Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Loading the FormsModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Simple SKU Form: @Component Annotation . . . . . . . . . . . . . . . . . . . . . . . 131
Simple SKU Form: template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Simple SKU Form: Component Definition Class . . . . . . . . . . . . . . . . . . . . . 135
Try it out! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Using FormBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Reactive Forms with FormBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
CONTENTS

Using FormBuilder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138


Using myForm in the view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
Try it out! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Adding Validations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Explicitly setting the sku FormControl as an instance variable . . . . . . . . . . . . . 143
Custom Validations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Watching For Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
ngModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Wrapping Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Using @angular/http . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
import from @angular/http . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
A Basic Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Building the SimpleHTTPComponent @Component . . . . . . . . . . . . . . . . . . . . . 157
Building the SimpleHTTPComponent template . . . . . . . . . . . . . . . . . . . . . . . 157
Building the SimpleHTTPComponent Controller . . . . . . . . . . . . . . . . . . . . . . 158
Full SimpleHTTPComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Writing a YouTubeSearchComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
Writing a SearchResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Writing the YouTubeService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
Writing the SearchBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Writing SearchResultComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
Writing YouTubeSearchComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
@angular/http API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Making a POST request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
PUT / PATCH / DELETE / HEAD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
RequestOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

Routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Why Do We Need Routing? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
How client-side routing works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
The beginning: using anchor tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
The evolution: HTML5 client-side routing . . . . . . . . . . . . . . . . . . . . . . . . 189
Writing our first routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Components of Angular 2 routing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Installing our Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
RouterOutlet using <router-outlet> . . . . . . . . . . . . . . . . . . . . . . . . . . 193
RouterLink using [routerLink] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
CONTENTS

Putting it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


Creating the Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
HomeComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
AboutComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
ContactComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Application Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Configuring the Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Routing Strategies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Path location strategy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Running the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Route Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
ActivatedRoute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Music Search App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
The SpotifyService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
The SearchComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Trying the search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
TrackComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Wrapping up music search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Router Hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
AuthService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
LoginComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
ProtectedComponent and Route Guards . . . . . . . . . . . . . . . . . . . . . . . . . . 229
Nested Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Configuring Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
ProductsComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Dependency Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242


Injections Example: PriceService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
“Don’t Call Us…” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Dependency Injection Parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Playing with an Injector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Providing Dependencies with NgModule . . . . . . . . . . . . . . . . . . . . . . . . . . . 250
Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Using a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Using a Factory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252
Using a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Using an alias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Dependency Injection in Apps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
Working with Injectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Substituting values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
NgModule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
CONTENTS

NgModule vs. JavaScript Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267


The Compiler and Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Dependency Injection and Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Component Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Specifying Providers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272

Data Architecture in Angular 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273


An Overview of Data Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Data Architecture in Angular 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

Data Architecture with Observables - Part 1: Services . . . . . . . . . . . . . . . . . . . . 275


Observables and RxJS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Note: Some RxJS Knowledge Required . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Learning Reactive Programming and RxJS . . . . . . . . . . . . . . . . . . . . . . . . 275
Chat App Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Implementing the Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
Implementing UserService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
currentUser stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Setting a new user . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
UserService.ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
The MessagesService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
the newMessages stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
the messages stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
The Operation Stream Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 288
Sharing the Stream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Adding Messages to the messages Stream . . . . . . . . . . . . . . . . . . . . . . . . . 291
Our completed MessagesService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Trying out MessagesService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
The ThreadsService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
A map of the current set of Threads (in threads) . . . . . . . . . . . . . . . . . . . . . 299
A chronological list of Threads, newest-first (in orderedthreads) . . . . . . . . . . . . 304
The currently selected Thread (in currentThread) . . . . . . . . . . . . . . . . . . . . 304
The list of Messages for the currently selected Thread (in currentThreadMessages) . . 306
Our Completed ThreadsService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Data Model Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
CONTENTS

Data Architecture with Observables - Part 2: View Components . . . . . . . . . . . . . . 312


Building Our Views: The ChatApp Top-Level Component . . . . . . . . . . . . . . . . . . 312
The ChatThreads Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
ChatThreads Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
ChatThreads template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
The Single ChatThread Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
ChatThread Controller and ngOnInit . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
ChatThread template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
ChatThread Complete Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
The ChatWindow Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
The ChatMessage Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
Setting incoming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
The ChatMessage template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
The Complete ChatMessage Code Listing . . . . . . . . . . . . . . . . . . . . . . . . . 334
The ChatNavBar Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
The ChatNavBar @Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
The ChatNavBar Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
The ChatNavBar template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
The Completed ChatNavBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Next Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

Introduction to Redux with TypeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345


Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Redux: Key Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Core Redux Ideas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
What’s a reducer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
Defining Action and Reducer Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . 348
Creating Our First Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Running Our First Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Adjusting the Counter With actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Reducer switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
Action “Arguments” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Storing Our State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
Using the Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Being Notified with subscribe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
The Core of Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
A Messaging App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Messaging App state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
Messaging App actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
Messaging App reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Trying Out Our Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
CONTENTS

Using Real Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368


Using Redux in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
Planning Our App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Setting Up Redux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
Defining the Application State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Defining the Reducers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
Defining Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
Creating the Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
CounterApp Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Providing the Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
Bootstrapping the App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
The CounterComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
The template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
The constructor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Putting It All Together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
What’s Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384

Intermediate Redux in Angular . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386


Context For This Chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Chat App Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
Reducers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Implementing the Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Thread . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
App State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
A Word on Code Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
The Root Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
The UsersState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
The ThreadsState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
Visualizing Our AppState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
Building the Reducers (and Action Creators) . . . . . . . . . . . . . . . . . . . . . . . . . 396
Set Current User Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
UsersReducer - Set Current User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
Thread and Messages Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Adding a New Thread Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . 398
Adding a New Thread Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
Adding New Messages Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . 400
CONTENTS

Adding A New Message Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401


Selecting A Thread Action Creators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
Selecting A Thread Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404
Reducers Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
Building the Angular Chat App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
The top-level ChatApp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
The ChatPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
Container vs. Presentational Components . . . . . . . . . . . . . . . . . . . . . . . . . 409
Building the ChatNavBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Redux Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
Threads Selectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Unread Messages Count Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
Building the ChatThreads Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
ChatThreads Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
ChatThreads template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
The Single ChatThread Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
ChatThread @Component and template . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Building the ChatWindow Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
The ChatMessage Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Setting incoming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
The ChatMessage template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430

Advanced Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432


Styling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
View (Style) Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
Shadow DOM Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
No Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
Creating a Popup - Referencing and Modifying Host Elements . . . . . . . . . . . . . . . 443
Popup Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Using ElementRef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
Binding to the host . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
Adding a Button using exportAs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
Creating a Message Pane with Transclusion . . . . . . . . . . . . . . . . . . . . . . . . . 452
Changing the host CSS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Using ng-content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Querying Neighbor Directives - Writing Tabs . . . . . . . . . . . . . . . . . . . . . . . . 455
Tab Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Tabset Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Using the Tabset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
Lifecycle Hooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
OnInit and OnDestroy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
OnChanges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
CONTENTS

DoCheck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
AfterContentInit, AfterViewInit, AfterContentChecked and AfterViewChecked . . . . 484
Advanced Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Rewriting ngIf - ngBookIf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Rewriting ngFor - ngBookRepeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
Change Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
Customizing Change Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
Zones . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
Observables and OnPush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517

Testing . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Test driven? . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
End-to-end vs. Unit Testing . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
Testing Tools . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Jasmine . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Karma . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Writing Unit Tests . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Angular Unit testing framework . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
Setting Up Testing . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
Testing Services and HTTP . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
HTTP Considerations . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
Stubs . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
Mocks . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
Http MockBackend . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
TestBed.configureTestingModule and Providers . . . . . . . . . . . . . . . . . . . . 527
Testing getTrack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528
Testing Routing to Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
Creating a Router for Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Mocking dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Spies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Back to Testing Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
fakeAsync and advance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
inject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Testing ArtistComponent’s Initialization . . . . . . . . . . . . . . . . . . . . . . . . . 544
Testing ArtistComponent Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 546
Testing ArtistComponent DOM Template Values . . . . . . . . . . . . . . . . . . . . . 547
Testing Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 550
Creating a ConsoleSpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
Installing the ConsoleSpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Configuring the Testing Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Testing The Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Refactoring Our Form Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
CONTENTS

Testing HTTP requests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560


Testing a POST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Testing DELETE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
Testing HTTP Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Testing YouTubeService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571

Converting an Angular 1 App to Angular 2 . . . . . . . . . . . . . . . . . . . . . . . . . . 572


Peripheral Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
What We’re Building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Mapping Angular 1 to Angular 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Requirements for Interoperability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
The Angular 1 App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
The ng1-app HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Code Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
ng1: PinsService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
ng1: Configuring Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
ng1: HomeController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
ng1: / HomeController template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
ng1: pin Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
ng1: pin Directive template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
ng1: AddController . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
ng1: AddController template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
ng1: Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
Building A Hybrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
Hybrid Project Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
Bootstrapping our Hybrid App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
What We’ll Upgrade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
A Minor Detour: Typing Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
Writing ng2 PinControlsComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
Using ng2 PinControlsComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 606
Downgrading ng2 PinControlsComponent to ng1 . . . . . . . . . . . . . . . . . . . . 607
Adding Pins with ng2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Upgrading ng1 PinsService and $state to ng2 . . . . . . . . . . . . . . . . . . . . . 611
Writing ng2 AddPinComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
Using AddPinComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
Exposing an ng2 service to ng1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
Writing the AnalyticsService . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
Downgrade ng2 AnalyticsService to ng1 . . . . . . . . . . . . . . . . . . . . . . . . 619
Using AnalyticsService in ng1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
CONTENTS

Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 39 - 2016-09-03 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 38 - 2016-08-29 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 37 - 2016-08-02 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 36 - 2016-07-20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 35 - 2016-06-30 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
Revision 34 - 2016-06-15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Revision 33 - 2016-05-11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Revision 32 - 2016-05-06 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
Revision 31 - 2016-04-28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 30 - 2016-04-20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 29 - 2016-04-08 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 28 - 2016-04-01 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 27 - 2016-03-25 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 26 - 2016-03-24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 25 - 2016-03-21 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 24 - 2016-03-10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 23 - 2016-03-04 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
Revision 22 - 2016-02-24 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Revision 21 - 2016-02-20 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Revision 20 - 2016-02-11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
Revision 19 - 2016-02-04 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Revision 18 - 2016-01-29 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Revision 17 - 2016-01-28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Revision 16 - 2016-01-14 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Revision 15 - 2016-01-07 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Revision 14 - 2015-12-23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Revision 13 - 2015-12-17 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Revision 12 - 2015-11-16 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Revision 11 - 2015-11-09 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Revision 10 - 2015-10-30 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 9 - 2015-10-15 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 8 - 2015-10-08 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 7 - 2015-09-23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 6 - 2015-08-28 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Revision 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Revision 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Revision 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Revision 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
CONTENTS 1

Book Revision
Revision 39 - Covers up to Angular 2 (2.0.0-rc.6, 2016-09-03)

Prerelease
This book is a prerelease version and a work-in-progress.

Bug Reports
If you’d like to report any bugs, typos, or suggestions just email us at: us@fullstack.io¹.

Chat With The Community!


We’re experimenting with a community chat room for this book using Gitter. If you’d like to hang
out with other people learning Angular 2, come join us on Gitter²!

Be notified of updates via Twitter


If you’d like to be notified of updates to the book on Twitter, follow @fullstackio³

We’d love to hear from you!


Did you like the book? Did you find it helpful? We’d love to add your face to our list of testimonials
on the website! Email us at: us@fullstack.io⁴.
¹mailto:us@fullstack.io?Subject=ng-book%202%20feedback
²https://gitter.im/ng-book/ng-book
³https://twitter.com/fullstackio
⁴mailto:us@fullstack.io?Subject=ng-book%202%20testimonial
CONTENTS 2


⁵mailto:carlos@ng-book.com
Writing your First Angular 2 Web
Application
Simple Reddit Clone
In this chapter we’re going to build an application that allows the user to post an article (with a
title and a URL) and then vote on the posts.
You can think of this app as the beginnings of a site like Reddit⁶ or Product Hunt⁷.
In this simple app we’re going to cover most of the essentials of Angular 2 including:

• Building custom components


• Accepting user input from forms
• Rendering lists of objects into views
• Intercepting user clicks and acting on them

By the time you’re finished with this chapter you’ll have a good grasp on how to build basic Angular
2 applications.
Here’s a screenshot of what our app will look like when it’s done:
⁶http://reddit.com
⁷http://producthunt.com
Writing your First Angular 2 Web Application 2

Completed application

First, a user will submit a new link and after submitting the users will be able to upvote or downvote
each article. Each link will have a score and we can vote on which links we find useful.
Writing your First Angular 2 Web Application 3

App with new article

In this project, and throughout the book, we’re going to use TypeScript. TypeScript is a superset of
JavaScript ES6 that adds types. We’re not going to talk about TypeScript in depth in this chapter, but
if you’re familiar with ES5 (“normal” javascript) / ES6 (ES2015) you should be able to follow along
without any problems.
We’ll go over TypeScript more in depth in the next chapter. So don’t worry if you’re having
trouble with some of the new syntax.
Writing your First Angular 2 Web Application 4

Getting started

TypeScript
To get started with TypeScript, you’ll need to have Node.js installed. There are a couple of different
ways you can install Node.js, so please refer to the Node.js website for detailed information:
https://nodejs.org/download/⁸ .

Do I have to use TypeScript? No, you don’t have to use TypeScript to use Angular 2, but
you probably should. ng2 does have an ES5 API, but Angular 2 is written in TypeScript
and generally that’s what everyone is using. We’re going to use TypeScript in this book
because it’s great and it makes working with Angular 2 easier. That said, it isn’t strictly
required.

Once you have Node.js setup, the next step is to install TypeScript. Make sure you install at least
version 1.7 or greater. To install it, run the following npm command:

1 $ npm install -g 'typescript@1.9.0-dev.20160409'

npm is installed as part of Node.js. If you don’t have npm on your system, make sure you
used a Node.js installer that includes it.

Windows Users: We’ll be using Linux/Mac-style commands on the commandline through-


out this book. We’d highly recommend you install Cygwin⁹ as it will let you run commands
just as we have them written out in this book.

Example Project
Now that you have your environment ready, let’s start writing our first Angular2 application!
Open up the code download that came with this book and unzip it. In your terminal, cd into the
first_app/angular2-reddit-base directory:

1 $ cd first_app/angular2-reddit-base

⁸https://nodejs.org/download/
⁹https://www.cygwin.com/
Writing your First Angular 2 Web Application 5

If you’re not familiar with cd, it stands for “change directory”. If you’re on a Mac try the
following:

1. Open up /Applications/Utilities/Terminal.app
2. Type cd, without hitting enter
3. In the Finder, Drag the first_app/angular2-reddit-base folder on to your termi-
nal window
4. Hit Enter Now you are cded into the proper directory and you can move on to the
next step!

Let’s first use npm to install all the dependencies:

1 $ npm install

Create a new index.html file in the root of the project and add some basic structure:

1 <!doctype html>
2 <html>
3 <head>
4 <title>Angular 2 - Simple Reddit</title>
5 </head>
6 <body>
7 </body>
8 </html>

Your angular2-reddit-base directory should look something like this:

1 .
2 |-- README.md // A helpful readme
3 |-- index.html // Your index file
4 |-- index-full.html // Sample index file
5 |-- node_modules/ // installed dependencies
6 |-- package.json // npm configuration
7 |-- resources/ // images etc.
8 |-- styles.css // stylesheet
9 |-- tsconfig.json // compiler configuration
10 `-- tslint.json // code-style guidelines

Angular 2 itself is a JavaScript file. So we need to add a script tag to our index.html document
to include it. But Angular has some dependencies itself:
Writing your First Angular 2 Web Application 6

Angular’s Dependencies

You don’t strictly need to understand these dependencies in-depth in order to use Angular
2, but you do need to include them. Feel free to skip this section if you’re not that interested
in the dependencies, but make sure you copy and paste these script tags.

To run Angular 2, we depend on these four libraries:

• core-js
• zone.js
• reflect-metadata
• SystemJS

To include them, add the following inside your <head>

1 <script src="node_modules/core-js/client/shim.min.js"></script>
2 <script src="node_modules/zone.js/dist/zone.js"></script>
3 <script src="node_modules/reflect-metadata/Reflect.js"></script>
4 <script src="node_modules/systemjs/dist/system.src.js"></script>

Notice that we’re loading these .js files directly from a directory called node_-
modules. The node_modules directory will be created when you run npm install. If
you don’t have a node_modules directory, make sure your shell was “in” the directory
angular2-reddit-base (e.g. by using cd angular2-reddit-base) when you typed npm
install.

CoreJS ES6 Shim

ES6 provides shims so that legacy JavaScript engines behave as closely as possible to ECMAScript 6.
This shim isn’t strictly needed for newer versions of Safari, Chrome, etc. but it is required for older
versions of IE.

What’s a shim? Perhaps you’ve heard about shims or polyfills and you’re not sure what
they are. A shim is code that helps adapt between cross browsers to a standardized behavior.
For instance, check out this ES6 Compatibility Table¹⁰. Not every browser is completely
compatible with every feature. By using different shims we’re able to get standardized
behavior across different browsers (and environments).
See also: What is the difference between a shim and a polyfill?¹¹
¹⁰https://kangax.github.io/compat-table/es6/
¹¹http://www.2ality.com/2011/12/shim-vs-polyfill.html
Writing your First Angular 2 Web Application 7

For more information on core-js checkout the project page¹².

Zones

Zone.js¹³ is an advanced topic that we don’t need to worry about much here. For know, just know
that it is a library used by Angular, primarily for detecting changes to data. (If you’re coming from
Angular 1, you can think of zones as an automatic version of $digest. If you’re not coming from
Angular 1, you can ignore it for now.)

Reflect Metadata

Angular itself was written in Typescript, and Typescript provides annotations for adding metadata
to code. Roughly speaking, the reflect-metadata package is a polyfill that lets us use this metadata.

SystemJS

SystemJS is a module loader. That is, it helps us create modules and resolve dependencies. Module
loading in browser-side javascript is surprisingly complicated and SystemJS makes the process much
easier.

All Dependencies Loaded


Now that we’ve added all of the dependencies, here’s how our index.html should look now:

1 <!doctype html>
2 <html>
3 <head>
4 <title>Angular 2 - Simple Reddit</title>
5 <!-- Libraries -->
6 <script src="node_modules/core-js/client/shim.min.js"></script>
7 <script src="node_modules/zone.js/dist/zone.js"></script>
8 <script src="node_modules/reflect-metadata/Reflect.js"></script>
9 <script src="node_modules/systemjs/dist/system.src.js"></script>
10
11 </head>
12 <body>
13 </body>
14 </html>

Adding CSS
We also want to add some CSS styling so that our app isn’t completely unstyled. Let’s include two
stylesheets as well:
¹²https://github.com/zloirock/core-js
¹³https://github.com/angular/zone.js/
Writing your First Angular 2 Web Application 8

1 <!doctype html>
2 <html>
3 <head>
4 <title>Angular 2 - Simple Reddit</title>
5 <!-- Libraries -->
6 <script src="node_modules/core-js/client/shim.min.js"></script>
7 <script src="node_modules/zone.js/dist/zone.js"></script>
8 <script src="node_modules/reflect-metadata/Reflect.js"></script>
9 <script src="node_modules/systemjs/dist/system.src.js"></script>
10
11 <!-- Stylesheet -->
12 <link rel="stylesheet" type="text/css"
13 href="resources/vendor/semantic.min.css">
14 <link rel="stylesheet" type="text/css" href="styles.css">
15 </head>
16 <body>
17 </body>
18 </html>

For this project we’re going to be using Semantic-UI¹⁴ to help with the styling. Semantic-UI
is a CSS framework, similar to Foundation or Twitter Bootstrap. We’ve included it in the
sample code download so all you need to do is add the link tag.

Our First TypeScript


Let’s now create our first TypeScript file. Create a new file called app.ts in the same folder and add
the following code:

Notice that we suffix our TypeScript file with .ts instead of .js The problem is our browser
doesn’t know how to interpret TypeScript files. To solve this, we’ll compile our .ts to a
.js file in just a few minutes.

¹⁴http://semantic-ui.com/
Writing your First Angular 2 Web Application 9

code/first_app/angular2-reddit-base/app.ts

1 /**
2 * A basic hello-world Angular 2 app
3 */
4 import {
5 NgModule,
6 Component
7 } from '@angular/core';
8 import { BrowserModule } from '@angular/platform-browser';
9 import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
10
11 @Component({
12 selector: 'hello-world',
13 template: `
14 <div>
15 Hello world
16 </div>
17 `
18 })
19 class HelloWorld {
20 }
21
22 @NgModule({
23 declarations: [ HelloWorld ],
24 imports: [ BrowserModule ],
25 bootstrap: [ HelloWorld ],
26 })
27 class HelloWorldAppModule {}
28
29 platformBrowserDynamic().bootstrapModule(HelloWorldAppModule);

This snippet may seem scary at first, but don’t worry. We’re going to walk through it step by step.
The import statements define the modules we want to use to write our code. Here we’re importing
four things: NgModule, Component, BrowserModule, and platformBrowserDynamic. We’ll be going
over each of these things in depth, so don’t worry if you aren’t sure what they do yet.
We import NgModule, Component from the module "@angular/core". The "@angular/core" portion
tells our program where to find the dependencies that we’re looking for.
Similarly, we import BrowserModule from the module "@angular/platform-browser" and plat-
formBrowserDynamic from the module "@angular/platform-browser-dynamic". We’ll talk about
these in a minute.
Writing your First Angular 2 Web Application 10

Notice that the structure of this import is of the format import { things } from wherever. In the
{ things } part what we are doing is called destructuring. Destructuring is a feature provided ES6
and we talk more about it in the next chapter.
The idea with the import is a lot like import in Java or require in Ruby: we’re pulling in these
dependencies from another module and making these dependencies available for use in this file.

Making a Component
One of the big ideas behind Angular 2 is the idea of components.
In our Angular apps we write HTML markup that becomes our interactive application. But the
browser only knows so many tags: the built-ins like <select> or <form> or <video> all have
functionality defined by our browser creator. But what if we want to teach the browser new tags?
What if we wanted to have a <weather> tag that shows the weather? Or what if we wanted to have
a <login> tag that creates a login panel?
That is the idea behind components: we teach the browser new tags that have new functionality.

If you have a background in Angular 1, Components are the new version of directives.

Let’s create our very first component. When we have this component written, we will be able to use
it in our HTML document like so:

1 <hello-world></hello-world>

So how do we actually define a new Component? A basic Component has two parts:

1. A Component annotation
2. A component definition class

Let’s take these one at a time.


If you’ve been programming in JavaScript for a while then this next statement might seem a little
weird:

1 @Component({
2 // ...
3 })
Writing your First Angular 2 Web Application 11

What is going on here? Well if you have a Java background it may look familiar to you: they are
annotations.
Think of annotations as metadata added to your code. When we use @Component on the HelloWorld
class, we are “decorating” the HelloWorld as a Component.
We want to be able to use this component in our markup by using a <hello-world> tag. To do that
we configure the @Component and specify the selector as hello-world.

1 @Component({
2 selector: 'hello-world'
3 })

If you’re familiar with CSS selectors, XPath, or JQuery selectors you’ll know that there are lots of
ways to configure a selector. Angular adds its own special sauce to the selector mix, and we’ll cover
that later on. For now, just know that in this case we’re defining a new tag.
The selector property here indicates which DOM element this component is going to use. This way
if we have any <hello-world></hello-world> tag within a template, it will be compiled using this
Component class.

Adding a template
We can add a template to our @Component by passing the template option:

1 @Component({
2 selector: 'hello-world',
3 template: `
4 <div>
5 Hello world
6 </div>
7 `
8 })

Notice that we’re defining our template string between backticks (` … `). This is a new (and
fantastic) feature of ES6 that allows us to do multiline strings. Using backticks for multiline strings
makes it easy to put templates inside your code files.
Writing your First Angular 2 Web Application 12

Should I really be putting templates in my code files? The answer is: it depends. For
a long time the commonly held belief was that you should keep your code and templates
separate. While this might be easier for some teams, for some projects it adds overhead
because you have switch between a lot of files.
Personally, if my templates are shorter than a page I much prefer to have the templates
alongside the code (that is, within the .ts file). When I can see both the logic and the view
together and it’s easy to understand how they interact with one another.
The biggest drawback to putting your views inlined with your code is that many editors
don’t support syntax highlighting of the internal strings (yet). Hopefully we’ll see more
editors supporting syntax highlighting HTML within template strings soon.
If you want to separate your template into a different file you can use the templateUrl key
to specify the URL of a template that will be loaded. More on this later.

Booting Our Application


Now that we have our hello-world component we need to boot our Angular app. One of the great
things about Angular is that it was built to work well with large apps that running in many different
environments. However, that means that we have to setup some configuration to describe the type
of app we want to boot.
For instance, we want to run this Angular app in our browser (vs., say, on a native module device
or on a server), and so we’re going to tell Angular that we need to load the browser dependencies.
Angular also has a powerful concept of modules. When you boot an Angular app, you’re not booting
a component directly, but instead you create an NgModule which points to the component you want
to load.
We’ll explain the details below, but let’s take another look at the code:

code/first_app/angular2-reddit-base/app.ts

22 @NgModule({
23 declarations: [ HelloWorld ],
24 imports: [ BrowserModule ],
25 bootstrap: [ HelloWorld ],
26 })
27 class HelloWorldAppModule {}
28
29 platformBrowserDynamic().bootstrapModule(HelloWorldAppModule);

The first thing we see is an @NgModule annotation. Like all annotations, this @NgModule( ... ) code
adds metadata to the class immediately following (HelloWorldAppModule).
Writing your First Angular 2 Web Application 13

Our @NgModule annotation has three keys: declarations, imports, and bootstrap.
declarations defines the components in this module. In this case, we just have one, but you often
have several.
imports describes which dependencies this module has. We’re creating a browser app, so we want
to import the BrowserModule.
bootstrap tells Angular that when this module is used to bootstrap an app, we and to load the
HelloWorld component as the top-level component.

Now that we have our @NgModule defined, we can boot the app. The last line does this.
Remember that Angular can run on different platforms and so when we say platformBrowser-
Dynamic() we’re telling Angular that we’re using a browser and we want to compile Angular
“dynamically” (e.g. when we open the page in our browser vs. ahead-of-time compiling, which
we’ll talk more about much later).
Now that we have a platform, we call .bootstrapModule() and give it our HelloWorldAppModule
as the starting point.
Once the application is bootstrapped, the HelloWorld component will be rendered where the <hello-
world></hello-world> snippet is on the index.html file. Let’s try it out!

We talk more about NgModules in the section on NgModules

Loading our Application


To run our application, we need to do two things:

1. we need to tell our HTML document to import our app file


2. we need to use our <hello-world> component

Add the following to the body section:


Another random document with
no related content on Scribd:
speak to Your Honour,’ replied he, ‘I own I am taken in an unhappy
affair, which neither malice nor inclination drew me into. But the
Head of the Country, notwithstanding I was the only child of my aged
parents, insisted, under great penalties, on my coming in to join him;
so that I beg you will pity me in my condition: but if it must be that I
die this night, pray! tell me what death you think it will be?’ Upon
which, not knowing what to think or what to say, I was somewhat at a
loss: his telling me of his aged parents, and his simplicity touched
me much: and how far I may be censured for my after-conduct, I
know not; but those who think I did amiss, I hope, will pardon me, as
being then but a young warrior. True, such a thing, I know, ought not
to have been publicly done; yet, when an opportunity presented itself
of doing an Act of Mercy without harm to the Cause, I am convinced
that this my behaviour will, with all generous minds, escape reproof.
The young boy continuing his lamentations, I told him to be of good
courage, for death was not so imminent as he expected; at which he
seemed to respire new vigor and life: And after some questions
asked, and promises made of his ever being grateful and upon his
telling me, that his home was not above fourteen miles from thence, I
asked him, if he could privately slip away thither. He replied, such a
favor would be too great for him to presume to request: So telling
him to do it if he could, I discharged him, ordering him to be a
support to his poor aged parents.
And now by this time we had almost conducted our prisoners to
Falkirk; and, after delivering them, we went thoroughly wet and cold,
to repose ourselves a little while on straw, and some in the open
fields or air, all places being by this time entirely filled, so that it was
then impossible to find any resource or ease for our excessive
hunger, wet and cold. So resting a few hours in that condition, they
soon after appeared; and when light, we went to see the field of the
slain; and number being made of them, we found near seven
hundred of the enemy slain, and about fifty of ours, which were
immediately interred. But this cheap-bought victory, you will say,
merited a better exit! The most distinguished among the slain were
Colonel Whitney and Sir Robert Monro, who was heard much to
blaspheme during the engagement, and as a punishment for which,
his tongue was miraculously cut asunder by a sword, that struck him
directly across the mouth. His brother, a physician, was likewise
killed at his side.[423] There were likewise found slain, some
Presbyterian Parsons,[424] who, fired with holy zeal, had quitted their
Bibles and took their swords. It was said, that one of these Parsons,
seeing the danger he was in of losing his life as a Soldier, had
recourse to his dignity, supposing that would be a cloak to save him.
‘Spare my life,’ said he to a Highlander, who was on the point of
taking it, ‘for I am a Minister of My Master Jesus Christ!’ To which the
other ingeniously replied: ‘If you are a good one, your Master has
need of you; if not, it’s fitting that you go and take your punishment
elsewhere!’—which dilemma was immediately solved by the
Highlander’s sword. Another Minister, seeing the case his Brother
was in, and being in a fair way to share the same fate, begged his
life of another Highlander for Prince Charles’s sake, by which means
he preserved what he would otherwise inevitably have lost.
We now took possession of the enemy’s baggage, camp, and
eight pieces of cannon; which they had not time to carry off—besides
a few prisoners, the chief of whom was Major Lockhart, who, after
having his life given him, and his liberty upon his parole of honour,
afterwards spurned against gratitude itself, by not only being
heinously perjured, but more than ordinarily thirsty of those
prisoners’ blood who just before had spared his life.[425]
We had now about one-hundred prisoners, one of whom seeing
his situation and ours, said with a grave countenance to his
companion: ‘By my soul, Dick, if Prince Charles goes on in this way,
Prince Frederick will never be King George!’ But of the five or six
thousand men that went with the Prince to the field of battle, scarce
three thousand returned back with him, for many of them, having
loaded themselves with booty, returned up to the hills. It was now a
great loss to us, that we had neither fort or other secure place to
keep our prisoners in, so that, if it were not merely out of mercy, it
was to no purpose to take prisoners, being without the means of
keeping them.
And now being come again to Stirling, the enemy being fled to
Edinburgh, and finding the siege of the Castle went on but slowly the
spirit of the army began much to change. Factions, grudges, and
private interest were now judged proper to be exercised, so that the
Prince was in a mortifying situation, seeing himself deserted by half
his army, and the others mightily turned. But as it is not for me to say
more than what relates to myself, I shall only mention the grudge I
have often dearly paid for—that exercised against my Colonel, who,
on the death of his brother had lately succeeded to the title of Lord
Balmerino. And here it may be proper to give some account of the
character of this brave man, which though sufficiently known, his
praises cannot enough be sung. He was a man of a noble
personage, of approved loyalty, and had the courage of a lion. He
possessed a mind and genius well ornamented with both natural and
acquired parts, being versed in most languages. He could recite
whole pages of Horace, Ovid, and Virgil at his age of fifty-eight, as
perfectly as a school-boy of sixteen, so that his memory for his years
was wonderful, the more so for its not being in the least impaired by
his hard drinking—his sole and predominant passion, which if he had
a little more restrained, he would have shone with the same lustre in
the army as he afterwards did on the scaffold. However, whilst with
the Prince, he was never failing with his duty; and proud he was of
having something, wherein he could shew his loyalty and obedience
to his Master.
But what was the cause of the quarrel betwixt him and Lord
George Murray, I know not; as Lord Balmerino did not ever directly
inform us why he was treated after that manner: only I remember,
His Lordship, when he saw himself so apparently ill-used, frequently
addressed his corps as follows. ‘Come let us do as we are ordered!
It is in vain to dispute; a time will come when I shall see all these
things righted, and that too at Lord George’s cost or mine. But at
present he is my superior, and we must obey as we tender the good
of the Prince.’ With such soothing expressions has he often accosted
us, when some were mutinying. And certainly he suffered a great
deal from Lord George, for, to my knowledge, we have been ordered
twenty or thirty miles, harassed and fatigued, and a courier sent after
us, ordering us immediately to return without halting—saying it was
my Lord George Murray’s orders.[426] And now a harder time than
ever came upon us, for I can safely say and prove, that from the time
of Falkirk Affair to the Battle of Culloden, notwithstanding the fatigue
of the day, I scarce slept three nights out of seven in bed.
And now having been some time before Stirling Castle, news
arrived from Edinburgh, that Cumberland was come thither with an
intention to rally General Hawley’s army and attack us again. As our
number had been so much diminished by the desertion of those who
after the battle of Falkirk had gone home loaded with plunder; it was
judged expedient for us to retire higher into the country, where we
were sure of being joined by some more forces. Accordingly we had
orders to proceed on our march; and on the morning on which we
began it, the Prince to St. Ringin,[427] distant about half a mile from
Stirling, to give the necessary directions for quitting the town and
raising the siege; which being done, we retired again, and when at a
short distance, we were surprized with a hideous noise just behind
us; and upon the Prince’s sending back to inquire what it was, it was
found to be a church blown up, just upon the place where a few
minutes before we had been standing. This church had been
converted into a magazine for our gun-powder, which by some
accident had been set on fire, and several of the town’s-people and
of our soldiers were killed by the explosion. However, continuing our
march, we arrived that night at Crieff a little town in the Highlands;
and the Prince lodged at Drummond Castle, the residence of the
illustrious Duke of Perth, which was only a short distance from the
said town. And now it was judged proper for the army to separate;
accordingly the Prince went the Highland way with the Highlanders
and prisoners for Inverness; and the Horse and Lowland Regiments
the Low-Country Road by the Sea-Coast, which was much longer, so
that it was three or four weeks before we again formed a junction.
And now we marched from Crieff to Perth, a large fine town; from
Perth to Cowpar-in-Angus; from Cowpar to Glams; from Glams to
Forfar; and so on to Montrose. The reason why I am so short in
mentioning these places, is, I have little to say; we passing them
quickly, and nothing extraordinary happening. But at Montrose we
halted a few days. It is a fine loyal seaport town and looked upon as I
was told there, to produce men of the greatest wisdom in Scotland.
Having staid three days there, we were a little surprised at the sight
of ships of war, that appeared a little distance off the Coast: and the
rumor being that Cumberland was pretty nigh us, we began to
apprehend lest they should land and intercept our passage; to
prevent which, we marched with all haste out of the town, the foot
going out the third day at night, and the rest following early the next
morning except the Hussars who remained some days longer to
watch the enemy’s motions.
Some of my readers may be curious to know what sort of men
these Hussars were. A set of braver fellows it would be very hard to
find; many of them having mounted themselves on horses which
they had taken from the enemy. Their Commander[428] also was a
wise, courageous virtuous man, and behaved himself in his station to
the admiration of all, regulating his corps with such order as to make
our enemies and the country, even fifty miles distant from us, have
more fear of them than almost the whole army. In fine, he was of
infinite service to the Prince, as also were his horse; for their conduct
was daring, and their courage was steeled, and few of them there
were, who would have scrupled to go, if possible to hell’s gates to
fetch away the keys.
Soon after our departure from Montrose, we arrived at Aberdeen,
where we staid two or three days; and notwithstanding our being in
the town the Presbyterian Ministers ceased not to preach and pray
publicly against us. And here it was that I happened to be bedfellow
to my Colonel, Lord Balmerino in the same bed where Cumberland
afterwards lay, it being in one of the Chief Provosts’ houses.
When we marched out of Aberdeen, it blew, snowed, hailed, and
froze to such a degree, that few Pictures ever represented Winter,
with all its icicles about it, better than many of us did that day; for
here men were covered with icicles hanging at their eyebrows and
beards; and an entire coldness seizing all their limbs, it may be
wondered at how so many could bear up against the storm, a severe
contrary wind driving snow and little cutting hail bitterly down upon
our faces, in such a manner that it was impossible to see ten yards
before us. And very easy it now was to lose our companions; the
road being bad and leading over large commons, and the paths
being immediately filled up with drifted snow. However, we continued
marching on till about three in the afternoon, when my horse
overcome by the inclemency of the weather, fairly gave it up and
would carry me no farther: and now by a little halt I quickly lost my
Company, and was obliged to alight and lead my horse leg-deep in
snow; being upon a wide common, as it appeared to me, not having
seen all that day’s march scarce a house, tree or barn. I now
expected every moment to perish, as I was quite benumbed and all
covered over with snow, and my horse refused to follow me. At last,
unable to proceed any farther, I sunk down, quite exhausted, upon
the snow. In this dreadful situation, I luckily recollected a little bottle
of spirits, which had been given me by the Provost’s Lady; and
accordingly tried to put my frozen hand into my riding-coat pocket to
take it out. On taking a draught of the liquor, I soon found that never
repose to the wearied traveller, never meat to a most ravenous
hunger, never drink to a most burning thirst, could be more
refreshing or agreeable than this was to me; and I should have
finished my bottle, if a reflection had not come into my head about
my poor horse, which seemed to be in as bad a situation as myself,
being one of a delicate and tender breed. Knowing that he could
drink beer, I resolved to make an experiment whether he would
partake of the contents of my bottle. So pouring the remainder of the
liquor into the crown of my hat, which I had pressed low down for the
purpose, and dissolving some snow in it, in order to mitigate the
spirits, I gave it my poor horse to drink: which to my great surprise
and pleasure, he did, his mouth, I believe, being so cold that he did
not know what he drank. However, now finding ourselves to respire
as it were new life and vigor, we endeavoured to proceed, and after
three quarters of an hour, being almost upon the relapse again, we
stumbled upon a house, and following the walls of it came to the
door, where entering together with my horse, I surprized the poor
people who were sitting at the fire. But they, seeing the condition I
was in, received me with a great deal of good-nature, and permitted
my horse to stand in the house till he was well rubbed, and then led
him to a little place for him to lie in, giving him hay and corn as he
wanted. After I had taken off my riding-coat and boots and well
warmed and refreshed myself, I heard of two more (who had been in
almost as bad a situation as myself except that their horses
continued to carry them), who were come to the next house
adjacent. So going out to see them, I found them to be two old
acquaintances, vizt., one Mr. Maxwell, and Mr. Ball, an English
Gentleman, who, after some chat, concluded, that two more
harassing marches, than that over the Esk and the present, could
scarcely be imagined. Accommodating ourselves as well as we
could for that night, being obliged to lie with our horses, we departed
early next morning for Old Meldrum, which place most of the army
had reached before us.
From Old Meldrum we marched the next day for Banff, a little
pretty agreeable town. About this time we heard, that the
Highlanders, who were with the Prince, had broke down the barracks
of Riven of Badenoch (which were a great eye-sore to them, having
been built to keep them in order), and having taken the Sergeant and
eleven more prisoners, were in full march for Inverness, distant
thence only twenty-four miles. And now, after a short stay at Banff,
we marched for Cullen; and by this time we heard that the Prince
had made himself master of the Lord President’s House, and after
some little resistance forced the soldiers in the town of Inverness to
retire into the Castle, which, after a regular siege, likewise soon
surrendered at discretion. About 200 men were taken prisoners here,
and several officers, the principal of whom were the Governor and
the Master of Ross. This rapid success of the Prince gave us great
courage. So, marching from Cullen, through Fochabers, over the
River Spey, Elgin, Forres and Nairn, towns only ten miles distant
from each other, we came to be greedy spectators of our dear Prince
again, and what he with his brave Highlanders had effected. And
now, to second our victorious arms, we were joined by several more
of the Clans and Chiefs, and the brave Amazon Lady McIntosh,[429]
Seaforth and others coming in, or causing their Clans to come in,
and many who had left us at Falkirk rejoining their colours, greatly
reinforced the army. When in this flourishing condition, it pleased the
Prince to make a visit to the Duke of Gordon’s, whither all the
Guards were ordered to attend him; and in going a curious fine
standard with this motto ‘Britons, strike home!’ that was taken at
Falkirk from Gardiner’s Dragoons, was honourably conferred upon
me by the Prince at the head of the whole Troop; and I had the
honor of carrying it ever after. Having passed Nairn, Forres, Elgin,
and the river Spey, just at the other side under Fochabers, we came
to the Duke’s seat.[430] What reception the Prince had, or what
passed there I know not: but after a short stay we attended our
Royal Master back again to Inverness. But as soon as we arrived
there, we had orders to conduct some of the chief officers, who had
lately been taken prisoners to Forres, and after leaving them there
(they being upon their parole of honor) to go to Cullen to inspect all
affairs there on that side of the country, and to observe the motions
of the enemy who lay at Aberdeen. While at Cullen, where we were
continually upon the watch by our patrolling parties, we heard that
Colonel Grant, a good French Officer, had with his Artillery taken
Fort Augustus, and made the garrison prisoners; that a part of Fitz-
James’ Horse had landed and joined the Prince;[431] and that Lord
George Murray had blocked up seven hundred men in the Castle of
Blair, when he behaved with a great deal of conduct and policy, for,
he appeared before the Castle with only a few men, having hid most
of the Highlanders with him in an adjacent wood. The garrison being
thus deceived made a sally upon him with about three hundred men;
but he immediately drew his party out of the wood and surrounded
them, upon seeing which, they immediately surrendered.[432] So,
sending them prisoners to Inverness he persevered in the siege of
the Castle: but the approach of the Hessians soon obliged him to
raise it and leave four hundred men remaining in the Castle.
At this time President Forbes together with Lord Loudon, were
endeavouring to confederate and knit together what forces they
could: but to prevent their doing much mischief, a party of the brave
McDonalds, with some few others, were detached under the
Command of the Duke of Perth, who soon dispersed this rising
power, and obliged its heads, viz., Lord Loudon and the President to
save themselves in boats.
Some of my readers may be curious to know who this President
was, and what interest he had. He may truly be styled the Oracle of
his Country, for many resorted to him for advice; and had he been as
great a friend as he was an implacable enemy, James would in all
probability have swayed the English sceptre; for by his interest,
cunning and persuasion he brought over his own party, together with
Sir Alexander McDonald and several others, who before were just
sworn in to the Prince’s interest.[433] So, I say, had he been as firm a
friend as he was an implacable enemy, we should have seen,
instead of the four thousand men who marched into England, an
army of Eighteen or twenty thousand men.
About this time we heard, that the officers who were prisoners
upon their parole of honour had broken it, and escaped to the
enemy’s army, all of them except the Master of Ross and one or two
more.[434] But what will the world say, to see these officers, whom no
tie of religion, gratitude or honour could bind, protected and
cherished by their own party—nay sent against us, to endeavour to
destroy those who before had saved them!
And now we heard, that the Advanced Guard of the enemy was
approaching us, and were got up to Strathbogie. We who were also
of the advanced Guard, upon receiving this intelligence, quitted
Cullen, and retreated to Fochabers, where a considerable body of
our men were endeavouring to make a resistance at the River Spey,
and had for that purpose built barracks, and made all necessary
preparations, in case the passage of the river had been attempted.
But finding their army lay quiet at Aberdeen, and that their advanced
party in Strathbogie only made now and then some little excursions
towards us as far as Keith, we, though at first we were very diligent
and alert, we relaxed in our vigilance, nay fell asleep and at last into
a lethargy, in which we unhappily continued till awakened by the foul
affair of Culloden, which merits an epithet bitterer than I can give.
About this time an advanced party under the command of Major
Glascow went out at night, and hearing that some of the enemy were
at Keith,[435] surrounded that place, and having taken most of them
prisoners, with their arms and equipage, returned the next day with
great honour to Spey-side, where Lord John Drummond and Lord
Ogilvy commanded.
As we lay hereabouts a considerable time, assessments were
made upon the country for our support, and among others upon the
Earl of Findlater’s Estate, who on our arrival had taken wing and
joined Cumberland Will. The Earl’s Steward, being threatened with
military executions, if he refused to comply with our demands (which
were always seconded by such threats, though seldom put in
practice) begged leave to write to his Master for instructions how to
act. Upon this the Earl, having consulted with Cumberland, sent a
Letter addressed To the Man they call Lord John Drummond, telling
his Lordship, that if he or any other person should pretend to
exercise any military authority over any thing belonging to him, there
were Rebels’ houses enough, on which his Master Cumberland
promised him he should have his revenge. This Letter excited a
great deal of indignation among us; and was the cause of what
afterwards happened to his house;—for several of our party, without
any order being given, and indeed without the Prince’s being in the
then situation of his affairs, able to restrain their fury, ransacked it,
and carried away several articles of value, but without setting fire to
it, or wantonly destroying anything merely for destroying’s sake.[436]
At last news arrived that the enemy had left Aberdeen, and were
marching against us.[437] This intelligence gave great satisfaction to
many of us, who were in a manner tired out of our lives. Yet
notwithstanding the approach of the enemy, all the Prince’s
endeavours to collect his whole army, were ineffectual; for many
under pretence of cultivating their lands, or promising to come up
soon enough, went, staid, and came as they thought proper.
And now finding the enemy advanced pretty fast both by water
and land, the fleet bringing up their provisions and wearied soldiers;
frequent patrols were sent out by us in order to observe their
motions. Here I had the honour of commanding the last patrolling
party that ever crossed the Spey for the Prince’s cause. Lord John
Drummond (Commander at the Spey) having ordered me with ten
others to patrol all night towards the enemy, we began our work
about seven o’Clock and continued it till about five the next morning,
being then eight miles from Fochabers and two from the enemy;
when we took a man with a Letter from one of Cumberland’s
Secretaries to the Duchess of Gordon,[438] desiring her to employ all
her interest among her vassals in getting down provisions and
getting together what forces she could, as the Duke of Cumberland
intended to pass the river that day. Having secured the Messenger
and Letter, we continued our route, till we came up in a manner to
where they were encamped; for as they lay upon the declivity of a
hill, and had no guards on the top, we were able to approach very
near to them unperceived. But finding them drawn out in order of
battle, after seeing all we could see, and some bravadoes and
huzzas, we retired with all speed, leaving them to wonder what we
meant. We soon reached Fochabers (on the Spey) where I found
Lord John Drummond. Having given him the Letter taken from the
Duke of Cumberland’s Messenger and informed him of the situation I
had found the enemy in, I retired to repose myself a little while.
When fast asleep, a servant came in to tell me that the enemy was in
the town, and that it was too late to think of escaping, almost all of
our party having already passed the river. However, starting up in
great confusion, I resolved to risk all rather than fall into their hands,
and mounting my horse escaped by a back road. I had no sooner
crossed the river than I was ordered to join a party of about eighty
horse who were to remain behind on the banks of the Spey to
observe the motions of the enemy; whilst the foot, amounting to
about two thousand men, marched for Inverness, where the Prince
then lay with the greatest part of his army. Finding that the enemy
after a short halt at the Spey side, began to cross the river, we
likewise retired and followed our foot, to inform them of the enemy’s
being in full pursuit of us. This intelligence made our men pass
through Elgin, without halting, and straight on that night to Forres,
which was ten miles farther; and, after some stay there, to Nairn, out
of which we were next morning driven; the whole English Army
entering the town at one end, whilst we marched out at the other,
and continuing to pursue us sharply for three or four hours. And here
it was His Grace the Duke of Perth and Colonel O’Sullivan[439]
gained immortal honour by their bravery and conduct in bringing us
off in good order from under the very nose of the enemy; for
notwithstanding all their firing upon our rear, and though we were
much inferior in numbers, we lost not one man.
Soon after their desisting from pursuing us, we received orders to
halt, and encamp upon that very place, where the fatal battle of
Culloden was afterwards fought. Having accordingly encamped as
well as we could on the heath that grew upon the common, which
served us both for bedding and fuel, the cold being very severe, we
were soon after joined by the Prince and several of his Clans.
Finding that the enemy did not pursue us we rested ourselves all that
night upon the Common, and early next morning drew out in battle-
array. But that day being Cumberland’s birthday,[440] and the enemy
shewing no intention to attack us on it, we reposed ourselves again,
though still keeping ourselves in readiness, upon the place where we
had rested the preceding night; a biscuit being given to us for our
refreshment. In that situation we remained, till the brave Prince came
amongst us in the dusk of the evening, with the full resolution of
going to attack them that night in their camp, distant only seven
miles. Orders were accordingly given to that effect, which were
obeyed with the greatest pleasure and alacrity by the whole army.
We began our March about seven o’Clock leaving great fires burning
in our camp: but by some strange infatuation or misfortune the road
was not rightly taken, either through the ignorance or treachery of
Lord George Murray’s guide. This still remains doubtful, but this I can
say, that with the little knowledge I had of the country I could have
conducted them much better and sooner. After we had marched till
about three o’Clock in the morning, over double the ground that was
necessary, we at last came pretty nigh the enemy’s camp: and when
we were supposing to surround them, and for that purpose in some
measure drawing out; my Lord George Murray began to be missing;
notwithstanding the Prince’s Aides-de-Camp in riding from rank to
rank, and asking, for God’s sake! what has become of His Lordship,
and telling that the Prince was in the utmost perplexity for want of
him. In that situation did we remain a considerable time, till, day
breaking fast in upon us, we heard that Lord George Murray was
gone off with most of the Clans. Where he had been all that
considerable time, or what was his intention in it, I leave Time to
prove. Now, after we had stood some time on the brink of entering
their camp, the Prince, on receiving the unwelcome news of Lord
George Murray’s going off with the greatest part of the army, was
under the necessity of ordering us likewise, much to our
dissatisfaction, to march back again to our Camp. In this manner did
that noble and well-concerted scheme fall to ruin—and not only to
ruin, but in such a manner as to ruin us, who before had hopes of
ruining the enemy. But O! for Madness! what can one think, or what
can one say here![441]
The enemy at our departure, being fully awakened and seeing
the jeopardy they had been in, judged rightly, it was their time now to
pursue us in the unhappy situation we were then in, being harassed,
hungry and starved and fatigued, almost to the greatest extremity.
We had no sooner reached our camp again, than news came of the
enemy’s being in full march towards us, and of their intention to
attack us. This disagreeable intelligence vexed us much in our
present situation, the more so, as of the twelve thousand men, who
were actually in arms and in the pay of the Prince, not above Four
thousand were now with him many going every moment,
notwithstanding his orders to the contrary, to Inverness, and to
woods and houses adjacent, in order to repose and rest themselves
after their late excessive fatigue. Many of these were so far from
rejoining us, that they were taken asleep by the enemy after the
battle. Those, however, who staid, put the best face on the affair they
could, and all of us presently appeared surprizingly courageous, who
only seemed to survive and animated by the spirit of loyalty and love
for our dear Prince. But now why we resolved to fight, or why we did
not retire to Inverness, and keep that town till we were fully joined,
which might have been easily done, or even at last, if judged proper,
avoided fighting and make another expedition into England in spite
of them,—I may say it was Fortune’s will;—for, contrary to the
Prince’s inclination, Lord George Murray insisted on standing and
fighting them that day: and as for what he said of our wanting
provisions, it is most certain, though we did that day, we might have
retired to Inverness and found there a sufficiency of meat for two or
three days. However, the Prince, notwithstanding his great inclination
to avoid fighting, was at last obliged to give way to the importunity of
Lord George Murray, who even used terms very cutting in case of
refusal; and was also for fighting His Grace the Duke of Perth—but
this may be said for him, he doubted not but the same Hand that had
supported and miraculously conducted the Prince hitherto would
infallibly continue to support him, and make him a glorious
Conqueror.[442]
I shall now proceed to give account in what manner we were
ranged in battle-array. The brave McDonalds, who till then had led
the van, and behaved at all times with great courage and bravery,
were now displaced, and made to give way, at the pleasure of Lord
George Murray, to the Athol men, whom he commanded. The rest of
the front line was composed of Highlanders: the second, of
Lowlanders and French, with four pieces of cannon at each wing:
and in the rear was the Prince attended by all the horse, and some
foot. In this manner were we drawn up—four thousand men to fight
eleven thousand. The enemy being by this time in full view, we
began to huzza and bravado them in their march upon us, who were
extended from right to left in battle-array, it being upon a common.
But, notwithstanding all our repeated shouts, we could not induce
them to return one: on the contrary, they continued proceeding, like a
deep sullen river; while the Prince’s army might be compared to a
streamlet running among stones, whose noise sufficiently shewed its
shallowness. The Prince, the Duke of Perth, the Earl of Kilmarnock,
Lord Ogilvy, and several other Highland and Lowland Chiefs, rode
from rank to rank, animating and encouraging the soldiers by well-
adapted harangues.
The battle being now begun, the whole fury of the enemy’s
Artillery seemed to be directed against us in the rear; as if they had
noticed where the Prince was. By the first cannon shot, his servant,
scarcely thirty yards behind him, was killed; which made some about
the Prince desire, that he would be pleased to retire a little off: but
this he refused to do, till seeing the imminent danger from the
number of balls that fell about him, he was by the earnest entreaties
of his friends forced to retire a little, attended only by Lord
Balmerino’s corps. Frequent looks and turns the Prince made, to see
how his men behaved: but alas! our hopes were very slender, from
the continual fire of musketry that was kept up upon them from right
to left. We had not proceeded far, when I was ordered back, lest the
sight of my standard going off, might induce others to follow. In
returning, various thoughts passed my soul, and filled by turns my
breast with grief for quitting my dear Prince, now hopes of victory,
then fear of losing—the miserable situation the poor loyalists would
again be reduced to—and what we had to expect if we left the field
alive: these thoughts, I say, strangely wrought upon me, till, coming
to the place I was on before, and seeing it covered with the dead
bodies of many of the Hussars who at the time of our leaving had
occupied it, I pressed on, resolving to kill or be killed. Some few
accompanied my standard, but soon left it. At this time, many of ours
from right to left were giving way and soon the battle appeared to be
irretrievably lost. The enemy, after we had almost passed the two
ranks, flanking and galling us with their continual fire, forced us at
last back, broke our first line, and attacked the second, where the
French troops were stationed. I happened then to be there, and after
receiving a slight grazing ball on my left arm, met with Lord John
Drummond, who, seeing me, desired I would come off with him,
telling me all was over and shewing me his regiment, just by him,
surrounded. Being quickly joined by about forty more horse, we left
the field of battle in a body, though pursued and fired upon for some
time. When we arrived at the foot of the hills, some of us took one
way, and some another: I, however, with about six more, continued
with Lord John Drummond; and it was with some difficulty we passed
the rapid torrents and frozen roads, till one o’Clock that night, when
we came to a little village at the foot of a great mountain, which we
had just crossed. Here we alighted, and some went to one house
and some to another. None of these cottages having the
conveniences to take in our horses, who wanted refreshment as well
as we, many of them perished at the doors. I happened to be in one
of the most miserable huts I had ever met with during my whole life;
the people were starving to death with hunger. However, having laid
myself down on the floor to rest myself after having been almost
thirty hours on horse-back; the people came crying about me and
speaking a language I did not understand, which made my case still
more unpleasant. But by good luck, a soldier soon after came in,
who could speak both to them and me, and brought with him some
meal, which was very acceptable, as I was almost starving with
hunger. Of this meal we made at that time a very agreeable dish, by
mixing it very thick with cold water, for we could get no warm: and so
betwixt eating and drinking we refreshed ourselves, till four o’Clock
in the morning; when Lord John Drummond and the rest of us began
our march, we knew not whither, through places it would be in vain to
describe; for we saw neither house, barn, tree, or beast nor any
beaten road, being commonly mid-leg deep in snow, till five o’Clock
that afternoon; when we found ourselves near a village called
Privana a Badanich,[443] the barracks of which, as I mentioned
before, the Prince had destroyed. Being now, to our surprize, almost
upon it, we consulted amongst ourselves how we might best get
intelligence from it; for, as it lay on the road from Inverness twenty-
four miles we apprehended the enemy might be there. But
fortunately a soldier coming out told us, that the village was occupied
by the Prince’s men. This intelligence gave us great pleasure; and
having accordingly entered the place, we found a great many of the
Prince’s adherents, the chief of whom was Lord George Murray and
the Duke of Perth; but we heard no news where the poor Prince was.
At first we had great hopes of rallying again: but they soon vanished,
orders coming for every one to make the best of his way he could.
So some went one way, some another: those who had French
Commissions surrendered; and their example was followed by my
Colonel, Lord Balmerino, tho’ he had none. Many went for the
mountains, all being uncertain what to do or whither to go.
In this perplexity I resolved to steer my course through the
mountainous country, notwithstanding the advice of many to the
contrary, who told me, it would be impossible for me to escape, and
begged I would go and surrender, assuring me, that if I attempted
the mountains, I should inevitably perish in them. But reflecting, how
nigh suffering my Father had been in the year 1715, taking Courage
and Patience for my guides, I resolved to enterprize a journey
through a Country that few of my Nation had ever passed before. So,
folding up my Standard, whose Motto was Britons! strike home! I put
it in my Riding-coat pocket, in hopes it might be of use another day,
and began my journey, in company with three others, for the
Highlands. Having discharged our horses, after a long day’s journey,
we came to a house situated on Garvie-more, twelve miles from any
other, where we met with many of our party, who had arrived there
before us. However, putting up in the best manner with what little we
could obtain, we set forward for Fort Augustus: but on the road, a
misfortune happened, that disconcerted all our plans; for a man who
carried our provisions of Oatmeal, fallen a little behind, by accident
met with some of the Brigade Picquets, who robbed him of our meal
and two riding-coats. This unexpected loss obliged us to separate
soon afterwards, being too many to subsist in this wild tract of
country, if we had kept together. However, having got betwixt Fort
Augustus and Fort William, we struck up into the country to the right,
and passed several large mountains in Lochiel’s Country, where we
staid three days, because we heard, that the brave Prince was nigh
us, and to take leave of one another, the necessaries of life being
exceedingly scarce, from the great number of people wandering over
the hills as well as we. I here went to wait upon the Duke of Perth,
who was at the house of Doctor Cameron, Lochiel’s Brother: but
being told by two sentinels at the door, that His Grace was
indisposed, I returned without seeing him. It was now reported, that
an English spy had been at Doctor Cameron’s house which obliged
me in all haste to quit that place; for certain it is, had I staid there any
longer, and the Highlanders supposed me to be the spy, they would
have made away with me. I therefore left my companions and set
forward to Lochaber, the wildest country I ever was in. And now it
was that I began to be truly miserable, and to endure hardships
which I had thought it impossible for human nature to support, for in
that most hideous place I was deprived of every thing that could give
me comfort: true it is, I found some few inhabitants; but in language
food and customs quite different from what I had ever seen before.
In this place I was forced to stay several days, on account of the
prodigious quantity of snow that fell upon the mountains, and
hindered me from discerning or making any road. During my stay, I
by good fortune got a pound of black bread to live upon. The snow
somewhat melting I set forward again from Lochaber towards the
sea-shore. On the road I was overtaken by about forty women, half-
starved to death who were wandering up and down for safety. Some
of them, who spoke English, told me, they had been driven out of
their houses by the soldiers who were sent out from Fort William to
ravage burn and plunder all before them and now it was that the
most heart-rending scenes of misery began to present themselves;
for many of these poor creatures with children in their arms, lay
extended in the clefts of the rocks half covered with snow, dead, and
a-dying in the most piteous manner. With these companions of
misery, and daily meeting with more I passed some days. I now
learned, that many of the unfortunate adherents of the Prince had
been famished to death on the hills and I expected it would soon be
my turn, for I began to be almost unable to proceed, my shoes being
worn out, and the sharp rocks wounding my feet. However, I
encouraged myself with the thought that my pursuers would have the
same difficulty to climb the rocks as I had; and on the twentieth
day[444] after our defeat at Culloden I came to the sea, in Clan-
Ronald’s Country; the view of which was most agreeable to me,
though even then I saw no prospect of escaping. Getting a little
refreshment from the people who dwelt on the sea-shore, I began as
it were to revive again, having been almost starved to death with
hunger and cold; for I had been obliged to lie down for whole nights
under the shelves of rocks, and was for two or three days together
without eating at all, as nothing could be obtained either for love or
money. Though I was fat and strong at the battle of Culloden, I was
now quite emaciated and reduced to so miserable a state, that, if I
had had another day to walk, I am sure I must have died; for I was
not only starved with hunger and cold, but frightfully covered with
vermin, which bit me all over my body so that there remained not
one whole place in my skin. This, joined with the pain in my torn feet,
made me often think that Job could not be in a more piteous
condition. Yet as he had God for his comforter, so had I; for the
justness of the cause I was suffering for, gave me great courage,
and supported me much: and though I saw daily enmities exercised
against me, it was a great satisfaction to me, to think, that, during the
time I had the honour of being a soldier under the banner of our dear
Prince, I could not accuse myself of one act that a Christian might
blush at.
Being somewhat recovered by the particular care of a worthy
Gentleman (whose kindness I had the satisfaction in a little time to
return by an agreeable meeting with him at Paris), I began to inquire,
if it were possible from island to island to make my escape out of the
country; for could I have sold myself at that time as a slave into
Turkey, I would have done it. My host told me, that it was impossible,
as all the boats had been destroyed by Cumberland’s order.
However, one morning, being in that perplexity of thought how to get
off, and fearing every moment the landing of soldiers to destroy the
country—news was brought us that two French ships had come into
the Lough just by—which mightily raised our hopes, that either a
restoration of the Prince’s affairs were at hand, or that we should
escape to France. So, running down to see and hear what we could
we found them to be ships destined for the Prince’s service, having
on board a great quantity of arms and ammunition, with five barrels
of gold, pretty large and nearly one-yard long—which before our late
fatal disasters might have been of great use.[445]
Notice being sent all about the Mountains, as far as time would
permit; several, who lay despairing, came down to the sea-shore,
and among the rest, my old patron the Duke of Perth, Lord John his
brother; Sir Thomas Sheridan, Secretary Murray, Mr. John Hay, and
Doctor Cameron. These being assembled together, judged it proper
though no one knew where the Prince was (many thinking he was
gone off for France) to have the money and arms brought on shore;
which was done on the evening after. Going securely to sleep that
night expecting to sail for France the next day, we were surprised by
the noise of cannon, which awakened us about three o’Clock in the
morning; and getting up to see what the matter was, we had for our
comfort the disagreeable news and sight of three English ships, that
were come from Fort William to attack the French, whose
appearance on the coast they had noticed, it seems. This sight
displeased us very much: however, fighting was the resolution of us
all. The two French Frigates (viz., the Mars and the Bellona), being
pretty strong, and having a sufficient quantity of men, cannon, and
ball, resolved to make head against the three English vessels, of
which one was the Baltimore,[446] that name being written upon her
rudder, which was carried off by a cannon-ball. The place they fought
in, was a creek of rocks, which held the French (the English coming
down upon them) as it were penn’d up, having the land on their back
and both sides. However it was easy for them to hold
communications with us on shore, who were four hundred armed
men or more; so that had they been obliged to abandon their Ships,
they might have saved themselves on shore. The Crews of the two
ships amounting to nearly eleven hundred men, might, with the
assistance of the Highlanders, have made an effectual resistance to
the English, if they had attempted to invade us. The battle furiously
beginning at three o’Clock in the morning, it remained doubtful till
four in the afternoon, who would be victors. Nor was it a small
pleasure to us to see those combatants engaged, and the skill of the
French, whose fire seldom missed the English; for many of us being
upon the rock as it were hung over these ships, in such a manner
that they could not hurt us with either cannon or musketry; we could
discern how matters went, and few balls were fired but we might see
whether they hit or missed, which latter the English frequently did.
During the engagement, the Highlanders were busied in carrying the
arms, money, and powder off from the sea-shore; which service they
performed with amazing resolution, many a cannon ball being fired,
in order to hinder them, by the largest of the English ships. Few
Highlanders there were but what had a cask of brandy hid privately
in the hills, with which some of them got merry before night. At last
we had the satisfaction to see the English hoist their sails, leave the
French, and sail to the main ocean. The French repaired their ships
as fast as possible, and endeavoured to make what haste out they
could, lest the English should return with a greater force.
All being over and hopes reviving again; one who had been in the
Guards with me, came and told me, he had found a barrel of money,
and that he would get me as much of it as I pleased. To this proposal
I replied, That I had no manner of use for it, for, if I should be so
fortunate as to escape into France, I had friends enough there, who
would take care of me; and that if I died or were taken, it would be of
no service to me. Moreover if the Prince should rally again, how
shocking it would be to have to reproach ourselves with being a
hindrance to our dear Prince’s designs. On hearing this reply, he,

You might also like