M A N N I N G Jeremy Wilken
Communicating between Angular components Angular applications are based around components that communicate with one another. You pass data into a child component using inputs and can emit events up to a parent component that shares data. This is essentially the way that normal HTML elements behave, which makes Angular easy to understand and learn. The figure below shows the structure of an example application used in chapter 5: It’s composed of a tree of components, much like what you see when creating HTML docu- ments. The Dashboard component has four child components: two instances of the Metric component and two of the Nodes component. The Dashboard component contains data, which it passes to each of its children using an input binding, which is how Angular shares data from a parent to a child component. In addition to sharing this data, Angular also keeps track of data changes and understands when to redraw the screen. App component #dashboard [cpu] (onRefresh) Navbar component Dashboard component Nodes Row component Nodes Row component Nodes Row component Nodes Row component Nodes Row component Nodes Row component [mem] [cluster1] [cluster2] Metric component Nodes component Nodes component Metric component Key: [Input bindings] (Emit output events) #Local template variable [node] [node] [node] [node] [node] [node] Inputs let us send data from a parent to a child, but outputs allow data to flow in the other direction. Similar to how events bubble up to their parent, outputs are Angular’s syntax for allowing a child to pass data or events back to its parent. In the figure, the Navbar component sends an output event to the App component. The App compo- nent waits until an output event is fired and then reacts accordingly. In this example, the App component refreshes the data on the page, but you can trigger any type of logic to execute. Angular provides other ways to communicate, such as using services or local template variables, which are covered in detail in this book.
Angular in Action JEREMY WILKEN MANN I NG Shelter ISland
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2018 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. ∞ Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Development editors: Cynthia Kane, Helen Stergius Review editor: Ivan Martinović Technical development editor: Alain Couniot Project editor: Kevin Sullivan Copyeditor: Corbin Collins Proofreader: Alyson Brener Technical proofreader: Tanya Wilke Typesetter: Happenstance Type- O-Rama Cover designer: Marija Tudor ISBN 9781617293313 Printed in the United States 1 2 3 4 5 6 7 8 9 10 - EBM - 23 22 21 20 19 18
To my parents, who gave me great encouragement, support, and latitude to become what I am today.
(This page has no text content)
v contents preface x acknowledgments xii about this book xiii about the author xvii about the cover illustration xviii 1 Angular: a modern web platform 1 1.1 Why choose Angular? 2 1.2 What you’ll learn 3 1.3 The journey from AngularJS to Angular 4 1.4 Angular: a platform, not a framework 5 Angular CLI 6 ■ Server rendering and the compiler 7 ■ Mobile and desktop capabilities 8 ■ UI libraries 9 1.5 Component architecture 11 Components’ key characteristics 13 ■ Shadow DOM 15 ■ Templates 17 ■ JavaScript modules 17 1.6 Modern JavaScript and Angular 20 Observables 21 1.7 TypeScript and Angular 23
vi contents 2 Building your first Angular app 25 2.1 Previewing the chapter project 26 2.2 Setting up the project 28 2.3 The basic app scaffolding 29 2.4 How Angular renders the base application 31 App component 31 ■ App module 32 ■ Bootstrapping the app 33 2.5 Building services 36 2.6 Creating your first component 38 2.7 Components that use components and services 44 2.8 Components with forms and events 47 2.9 Application routing 50 3 App essentials 54 3.1 Entities in Angular 55 Modules 57 ■ Components 58 ■ Directives 60 ■ Pipes 62 ■ Services 63 3.2 How Angular begins to render an app 64 3.3 Types of compilers 65 3.4 Dependency injection 66 3.5 Change detection 67 3.6 Template expressions and bindings 68 Interpolation 69 ■ Property bindings 70 ■ Special property bindings 71 ■ Attribute bindings 72 ■ Event bindings 73 4 Component basics 76 4.1 Setting up the chapter example 77 Getting the code 79 4.2 Composition and lifecycle of a component 79 Component lifecycle 81 ■ Lifecycle hooks 83 ■ Nesting components 84 4.3 Types of components 85 4.4 Creating a Data component 89
viicontents 4.5 Using inputs with components 91 Input basics 92 ■ Intercepting inputs 95 4.6 Content projection 97 5 Advanced components 104 5.1 Change detection and optimizations 105 5.2 Communicating between components 108 Output events and template variables 110 ■ View Child to reference components 112 5.3 Styling components and encapsulation modes 113 Adding styles to a component 114 ■ Encapsulation modes 116 5.4 Dynamically rendering components 119 Using the ng-bootstrap modal for dynamic components 120 ■ Dynamically creating a component and rendering it 123 6 Services 128 6.1 Setting up the chapter example 129 Getting the chapter files 131 ■ Sample data 131 6.2 Creating Angular services 132 6.3 Dependency injection and injector trees 137 6.4 Services without dependency injection 141 6.5 Using the HttpClient service 142 HttpInterceptor 146 6.6 Helper services 149 6.7 Services for sharing 153 6.8 Additional services 157 7 Routing 159 7.1 Setting up the chapter example 160 7.2 Route definitions and router setup 162 7.3 Feature modules and routing 165 7.4 Route parameters 167 Creating links in templates with routerLink 167 ■ Accessing the route parameters in a component 168
viii contents 7.5 Child routes 170 7.6 Secondary routes 173 Defining a secondary route 174 ■ Navigating between secondary routes 175 ■ Closing a secondary route and programmatic routing 176 7.7 Route guards to limit access 177 7.8 Lazy loading 182 7.9 Routing best practices 185 8 Building custom directives and pipes 188 8.1 Setting up the chapter example 189 8.2 Crafting custom directives 190 Creating an attribute directive 192 ■ Modifying a component with a directive with events 194 ■ Creating a structural directive 197 8.3 Crafting custom pipes 199 Creating a pure pipe 201 ■ Creating an impure pipe 203 9 Forms 208 9.1 Setting up the chapter example 209 Review the app before starting 211 9.2 Template-driven forms 212 Binding model data to inputs with NgModel 212 ■ Validating form controls with NgModel 214 ■ Custom validation with directives 217 ■ Handling submit or cancel events 219 9.3 Reactive forms 221 Defining your form 222 ■ Implementing the template 224 ■ Watching changes 226 ■ Custom validators with reactive forms 227 ■ Handling submit or cancel events 230 ■ Which form approach is better? 234 9.4 Custom form controls 235 10 Testing your application 242 10.1 Testing tools and setting up the chapter example 243 Testing tools 244
ixcontents 10.2 Unit testing 244 Anatomy of unit tests 245 ■ Testing pipes 246 ■ Testing services, stubs, and mocking HTTP requests 247 ■ Testing components and using testing modules 253 ■ Testing directives 261 10.3 e2e testing 265 10.4 Additional testing strategies 270 How much testing is enough? 271 ■ When do I write tests? 271 ■ What do I write, e2e or unit tests? 272 ■ What if I don’t have time to write tests? 272 ■ What about other types of testing? 273 11 Angular in production 275 11.1 Building Angular for production 276 Production build 276 ■ Optimizing for target browsers 277 ■ Progressive Web Apps 277 ■ Internationalization (i18n) 278 ■ Using alternative build tooling 278 ■ Server-side rendering or pre- rendering 279 ■ Build pipelines 280 11.2 Angular architecture choices 280 Lazy load routes 280 ■ Reduce external dependencies 281 ■ Stay up-to-date 284 11.3 Deployment 284 appendix Upgrading from AngularJS to Angular 287 index 293
x preface A major framework for many years, Angular has influenced a generation of web tech- nologies. Even developers who haven’t used it have benefitted from its existence, as it helped popularize a number of important concepts and technologies. Early in its AngularJS days (version 1.x is known as AngularJS), it became perhaps the most popular web application framework of its time. But the 1.x version had lim- itations, and a number of optimizations were built into the framework. The concept of two-way databinding (being able to sync data between the controller and the view automatically), which was touted early on as its best feature, became a performance bottleneck in large applications that abused its utility. To help mitigate this problem, one-way and one-time binding options were introduced to improve performance, but they required developers to opt in. Also, components were introduced as a better way to organize and structure applications, but taking advantage of them required refactoring of existing applications. You could build an amazing and performant application with AngularJS 1.x, but it wasn’t always the default mode and required unlearning concepts that were believed to be best practices from earlier releases. Simply put, writing well-designed applica- tions was possible because of workarounds from the original concepts that AngularJS embraced. Instead of evolving the version 1.x codebase, the decision was made to rewrite it from scratch to implement the lessons learned into the foundations of the next major ver- sion. This was a multiyear endeavor that involved both the Angular team at Google and the larger community of early adopters. It was a long journey, and I rode alongside and built applications on top of it during early alpha and beta phases. The final result of that
xi preface journey was Angular 2.0 (version 2.0 and above is known as just Angular), and its com- munity has grown rapidly since its release. I started working on Angular in Action while Angular was still in early beta for ver- sion 2.0. Angular then underwent regular and rapid iterations during the book’s writ- ing and development. But today Angular is stable and evolves with a well-defined release cycle for new features and deprecations. The book examples are written to work with Angular 5 and above, and going forward, the GitHub projects will have notes about any required changes to keep up with Angular’s evolution.
xii acknowledgments I’d like to thank first and foremost my wife, Linda, for her patience and understanding as I wrote this book, largely during the evening and weekend hours. I appreciate your support, and I pledge to make up some of the lost time. Manning provided a team of professionals dedicated to making this book happen. Dozens of individuals were involved, including my developmental editors Helen Ster- gius and Cynthia Kane, technical developmental editor Alain Couniot, technical proof- reader Tanya Wilke, and review editor Ivan Martinović. Several external reviewers also provided helpful feedback on different stages of the manuscript: Harsh Raval, Kumar Unnikrishnan, Michael A. Angelo, Phily Austria, Radoslaw Pilski, and Tony Brown. Along with that team were others at Manning who helped manage the cycle of early releases and the final production release, including project editor Kevin Sullivan, copy- editor Corbin Collins, and proofreader Alyson Brener. A big thank you goes to the Angular team for creating Angular and also for the oppor- tunities they’ve given me to talk with team members individually. Google also sponsors the Google Developer Experts program, which has a great list of Angular experts who have been helpful and which I’m proud to belong to. I also want to thank Jason and David Aden for their early contributions and time working on the manuscript with me. Finally, thank you, the reader, for picking up this book to spend your precious time with me between these pages. If it weren’t for you, I wouldn’t have a reason to write. I hope to hear from you and see what you build!
xiii about this book Angular in Action is designed to help you learn how to use Angular in building your own web applications. I’ve brought the core lessons from my own experiences into this book. I’ve built a number of large enterprise applications on Angular and many smaller ones as well. I believe similar best practices go into most well-written applica- tions no matter their size, so I share those as well. My goal is to ensure you have a strong foundation in how Angular works, how it’s used to build web applications, and how to then ship those into production. This foun- dational knowledge will enable you to learn additional concepts more quickly and eas- ily (often by reviewing the documentation or even blog posts). There are certainly more Angular topics than could be covered in a single book, as Angular is an ambitious and comprehensive set of tools and libraries. I took great care to make this a book that works on multiple levels. You may find some topics to be more advanced than you need right now, but you can always come back to them later. Or you may find that the basics are familiar but the more advanced topics help fill in the gaps. Who should read this book Although I believe Angular is accessible for developers, this book is targeted at readers who have the subject knowledge detailed in the following list. Other readers will certainly find value in the content, but may have knowledge gaps that aren’t covered specifically: ¡ Web applications —You understand the role of web applications and have a little bit of experience with building them. ¡ JavaScript —You have enough knowledge of JavaScript and its syntax to be able to follow along with the examples. ¡ HTML/CSS —You understand the roles of HTML and CSS, as well as their syntax.
xiv about this book I mention some topics in the book that are important but not part of Angular. You may know nothing about some of these, but the book provides enough cursory knowledge that you should be able to follow along: ¡ TypeScript —Angular is written with TypeScript, and so are all the examples in this book. If you’re new to TypeScript, I provide many hints along the way, but I sug- gest you review the official documentation at www.typescriptlang.org. ¡ Reactive programming —Angular’s design often allows and recommends using reactive-style programming, which is usually used in conjunction with the popu- lar RxJS library. There’s a lot of great material out there for learning reactive and RxJS, and I share a few links to it in the book. How this book is organized This book is divided into themed chapters, beginning with the core details of Angu- lar and expanding into more complex themes. Chapters 1–3 lay the groundwork for understanding what Angular is (and isn’t) and discuss its role in building your appli- cations. These chapters also provide a quick but fairly comprehensive tutorial of many of Angular’s key features. If you’re already familiar with Angular, you may find these sections easy to skim to find new insights. Chapters 4–5 act like a single unit on the topic of components. Angular (like HTML) is based on the idea of building individual components that can be composed together for more complex interactions. You can’t have an Angular application without com- ponents, and I cover them in great detail in these chapters so you can focus on other aspects in the remainder of the book. Chapters 6–9 focus on key topics in building applications. Chapter 6 is all about ser- vices and, subsequently, dependency injection. Understanding how to manage your services is key to building a larger Angular application, and often key to using other capabilities as well. Chapter 7 looks closely at the router and how to use it to create simple to complex navigation patterns that are used in many web applications. Chapter 8 shows you how to build your own custom directives and pipes, which become crucial when you expand the size of your application and want to make it easier to maintain. Finally, chapter 9 covers the two different approaches to building forms with Angular, as well as how to create your own custom form controls. The last two chapters round off your Angular training with a focus on testing in chap- ter 10 and on building and deploying your application for production in chapter 11. You might build some small hobby websites without testing or production tooling, but Angular provides some great tools that make it easy even for large enterprise applica- tions to use. I suggest you use them too! The brief appendix discusses the transition from AngularJS to Angular (or version 1.x to 2+). If you’re brand new to Angular and want a guided tour, I recommend reading the chapters in order. This approach will give you incremental knowledge to build on as you go, as often a chapter glosses over details that were covered in an earlier one.
xvabout this book If you have some prior experience with Angular or are interested in particular topics, feel free to head straight for those chapters. I believe you can skim early sections that cover familiar material and then look more closely at later parts of a chapter to learn more complex capabilities. As you skim, keep an eye out for diagrams that explain var- ious concepts; they’re a great way to quickly validate whether you understand the topic at hand. If there are unfamiliar concepts, you can always refer to other chapters. Most chapters feature fairly extensive examples. In order to do them properly, you’ll have to follow along through the whole chapter. The final versions of the code are pro- vided if you don’t want to follow the examples and build the code yourself, but I strongly encourage you to code along. You’ll understand the coding and retain the informa- tion more effectively that way. If you run into any issues with a chapter example, you can check the GitHub project for any potential code changes that were required after the book’s publication (such as if a breaking change has been introduced in Angular). Stack Overflow is also a great place to ask any questions that extend beyond the chapter example code. About the code All the code in this book can be downloaded from GitHub at https://github.com/ angular-in-action. (A zip file containing the complete code at time of publication will also be available from the publisher’s website at https://www.manning.com/books/ angular-in-action.) Each chapter also provides a link to the specific chapter content, so you don’t need to download everything ahead of time. You’ll need to have a recent version of NodeJS installed on your machine. Chap- ter 1 covers more specific things to install for the Angular CLI. You also need a modern browser—preferably one that has good debugging tools, like Chrome. If you’re run- ning an outdated browser (like IE10), the code won’t run, so update your browser for compatibility and security. This book contains many examples of source code, both in numbered listings and inline with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code, has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the list- ings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. Book forum Purchase of Angular in Action includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical
xvi about this book questions, and receive help from the author and from other users. To access the forum, go to https://forums.manning.com/forums/angular-in-action. You can also learn more about Manning's forums and the rules of conduct at https://forums.manning. com/forums/about. Manning’s commitment to our readers is to provide a venue where a meaningful dia- logue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.
xvii about the author Jeremy Wilken is a software engineer with a passion for designing applications and technology solutions that focus on improving the lives of users. He is a Google Devel- oper Expert for Web Technologies and Angular as well as the Google Assistant, which is an endorsement from Google as a subject matter expert and community leader in Angular and the web. Most of his day-to-day work is in building Angular applications, but he also spends a lot of time and energy speaking at events, running workshops and trainings, writ- ing, and helping build community through meetups and conferences. He’s worked for companies like eBay, Teradata, and VMware, and has been a consultant for many years. He lives in Austin, Texas, with his wife and two daughters. Outside of the tech world, he is a certified beer judge (it’s a real thing) and brews his own beer.
xviii about the cover illustration The figure on the cover of Angular in Action is captioned “A colonel of the Strelitzes, the old Russian militia and body guard to the czars of Moscovy.” The illustration is taken from Thomas Jefferys’ A Collection of the Dresses of Different Nations, Ancient and Modern (four volumes), London, published between 1757 and 1772. The title page states that these are hand-colored copperplate engravings, heightened with gum arabic. Thomas Jefferys (1719–1771) was called “Geographer to King George III.” He was an English cartographer who was the leading map supplier of his day. He engraved and printed maps for government and other official bodies and produced a wide range of commercial maps and atlases, especially of North America. His work as a map maker sparked an interest in local dress customs of the lands he surveyed and mapped, which are brilliantly displayed in this collection. Fascination with faraway lands and travel for pleasure were relatively new phenomena in the late eighteenth century, and collections such as this one were popular, introducing both the tourist as well as the armchair trav- eler to the inhabitants of other countries. The diversity of the drawings in Jefferys’ volumes speaks vividly of the uniqueness and individuality of the world’s nations some 200 years ago. Dress codes have changed since then, and the diversity by region and country, so rich at the time, has faded away. It’s now often hard to tell the inhabitants of one continent from another. Perhaps, try- ing to view it optimistically, we’ve traded a cultural and visual diversity for a more varied personal life—or a more varied and interesting intellectual and technical life. At a time when it’s difficult to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Jefferys’ pictures.
Comments 0
Loading comments...
Reply to Comment
Edit Comment