Jeremy Wilken - программист

Transcription

Jeremy WilkenMANNING

Communicating between Angular componentsAngular applications are based around components that communicate with oneanother. You pass data into a child component using inputs and can emit events upto a parent component that shares data. This is essentially the way that normal HTMLelements behave, which makes Angular easy to understand and learn.The figure below shows the structure of an example application used in chapter 5: It’scomposed of a tree of components, much like what you see when creating HTML documents. The Dashboard component has four child components: two instances of the Metriccomponent 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 sharesdata from a parent to a child component. In addition to sharing this data, Angular alsokeeps track of data changes and understands when to redraw the ardcomponent[cpu]Metriccomponent[node]Nodes de]Nodes Rowcomponent[Input bindings](Emit output events)#Local template variable[cluster1]Nodescomponent[node]Nodes Rowcomponent[cluster2]Nodescomponent[node]Nodes Rowcomponent[node]Nodes Rowcomponent[node]Nodes RowcomponentInputs let us send data from a parent to a child, but outputs allow data to flow in theother direction. Similar to how events bubble up to their parent, outputs are Angular’ssyntax for allowing a child to pass data or events back to its parent. In the figure, theNavbar component sends an output event to the App component. The App component 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 oflogic to execute. Angular provides other ways to communicate, such as using servicesor local template variables, which are covered in detail in this book.

Angular in ActionJEREMY WILKENMANNINGShelter 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, pleasecontactSpecial Sales DepartmentManning Publications Co.20 Baldwin RoadPO Box 761Shelter Island, NY 11964Email: 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 formor by means electronic, mechanical, photocopying, or otherwise, without prior written permission of thepublisher.Many of the designations used by manufacturers and sellers to distinguish their products are claimedas trademarks. Where those designations appear in the book, and Manning Publications was aware of atrademark 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 bookswe publish printed on acid- free paper, and we exert our best efforts to that end. Recognizing also ourresponsibility to conserve the resources of our planet, Manning books are printed on paper that is atleast 15 percent recycled and processed without the use of elemental chlorine.Manning Publications Co.20 Baldwin RoadPO Box 761Shelter Island, NY 11964Development editors:Review editor:Technical development editor:Project editor:Copyeditor:Proofreader:Technical proofreader:Typesetter:Cover designer:ISBN 9781617293313Printed in the United States1 2 3 4 5 6 7 8 9 10 - EBM - 23 22 21 20 19 18Cynthia Kane, Helen StergiusIvan MartinovićAlain CouniotKevin SullivanCorbin CollinsAlyson BrenerTanya WilkeHappenstance Type- O-RamaMarija Tudor

To my parents, who gave me great encouragement, support, and latitude to becomewhat I am today.

contentspreface xacknowledgments xiiabout this book xiiiabout the author xviiabout the cover illustration1xviiiAngular: a modern web platform11.1Why choose Angular?21.2What you’ll learn1.3The journey from AngularJS to Angular 41.4Angular: a platform, not a framework 53Angular CLI 6 Server rendering and the compilerand desktop capabilities 8 UI libraries 9 7 1.5Component architecture11Components’ key characteristics 13 ShadowDOM 15 Templates 17 JavaScript modules 17 1.6Modern JavaScript and Angular 20Observables1.7 21TypeScript and Angularv23 Mobile

vicontents2Building your first Angular app2.1Previewing the chapter project 262.2Setting up the project 282.3The basic app scaffolding 292.4How Angular renders the base applicationApp componentapp 3332531 App module32 31Bootstrapping the2.5Building services 362.6Creating your first component 382.7Components that use components and services2.8Components with forms and events2.9Application routingApp essentials3.144475054Entities in Angular 55Modules 57 ComponentsPipes 62 Services 63 58 Directives60 3.2How Angular begins to render an app 643.3Types of compilers 653.4Dependency injection3.5Change detection3.6Template expressions and bindings 686667Interpolation 69 Property bindings 70 Special propertybindings 71 Attribute bindings 72 Event bindings 73 4Component basics4.1 76Setting up the chapter example77Getting the code 794.2Composition and lifecycle of a component 79Component lifecyclecomponents 8481 Lifecycle hooks4.3Types of components 854.4Creating a Data component 8983 Nesting

viicontents 4.5Using inputs with components 91Input basics 924.65Intercepting inputs 95 Content projection 97Advanced components1045.1Change detection and optimizations1055.2Communicating between components 108Output events and template variables 110reference components 1125.3View Child toStyling components and encapsulation modesAdding styles to a component 1145.4 113Encapsulation modes 116Dynamically rendering components 119Using the ng-bootstrap modal for dynamiccomponents 120 Dynamically creating a component andrendering it 123 6Services6.1128Setting up the chapter exampleGetting the chapter files 129Sample data1316.2Creating Angular services6.3Dependency injection and injector trees6.4Services without dependency injection 1416.5Using the HttpClient service 142HttpInterceptor71311371466.6Helper services6.7Services for sharing 1536.8Additional servicesRouting1321491571597.1Setting up the chapter example1607.2Route definitions and router setup7.3Feature modules and routing 1657.4Route parameters 167162Creating links in templates with routerLinkroute parameters in a component 168167 Accessing the

viiicontents7.5Child routes 1707.6Secondary routes173Defining a secondary route 174 Navigating between secondaryroutes 175 Closing a secondary route and programmaticrouting 176 87.7Route guards to limit access7.8Lazy loading 1827.9Routing best practices 185177Building custom directives and pipes8.1Setting up the chapter example8.2Crafting custom directives188189190Creating an attribute directive 192 Modifying a component witha directive with events 194 Creating a structural directive 197 8.3Crafting custom pipes199Creating a pure pipe 2019Forms9.1 Creating an impure pipe208Setting up the chapter exampleReview the app before starting9.2203Template-driven forms209211212Binding model data to inputs with NgModel 212 Validatingform controls with NgModel 214 Custom validation withdirectives 217 Handling submit or cancel events 219 9.3Reactive forms 221Defining your form 222 Implementing thetemplate 224 Watching changes 226 Custom validatorswith reactive forms 227 Handling submit or cancelevents 230 Which form approach is better? 234 9.410Custom form controlsTesting your application23524210.1 Testing tools and setting up the chapter example 243Testing tools 244

ixcontents10.2 Unit testing 244Anatomy of unit tests 245 Testing pipes 246 Testingservices, stubs, and mocking HTTP requests 247 Testingcomponents and using testing modules 253 Testingdirectives 261 10.3 e2e testing 26510.4 Additional testing strategies270How much testing is enough? 271 When do I writetests? 271 What do I write, e2e or unit tests? 272 What ifI don’t have time to write tests? 272 What about other types oftesting? 273 11Angular in production27511.1 Building Angular for production276Production build 276 Optimizing fortarget browsers 277 Progressive WebApps 277 Internationalization (i18n) 278 Usingalternative build tooling 278 Server-side rendering or prerendering 279 Build pipelines 280 11.2 Angular architecture choices280Lazy load routes 280 Reduce externaldependencies 281 Stay up-to-date 284 11.3 Deployment 284appendix Upgrading from AngularJS to Angularindex293287

prefaceA major framework for many years, Angular has influenced a generation of web technologies. Even developers who haven’t used it have benefitted from its existence, as ithelped popularize a number of important concepts and technologies.Early in its AngularJS days (version 1.x is known as AngularJS), it became perhapsthe most popular web application framework of its time. But the 1.x version had limitations, and a number of optimizations were built into the framework. The conceptof two-way databinding (being able to sync data between the controller and the viewautomatically), which was touted early on as its best feature, became a performancebottleneck in large applications that abused its utility. To help mitigate this problem,one-way and one-time binding options were introduced to improve performance, butthey required developers to opt in. Also, components were introduced as a better way toorganize and structure applications, but taking advantage of them required refactoringof existing applications.You could build an amazing and performant application with AngularJS 1.x, but itwasn’t always the default mode and required unlearning concepts that were believedto be best practices from earlier releases. Simply put, writing well-designed applications was possible because of workarounds from the original concepts that AngularJSembraced.Instead of evolving the version 1.x codebase, the decision was made to rewrite it fromscratch to implement the lessons learned into the foundations of the next major version. This was a multiyear endeavor that involved both the Angular team at Google andthe larger community of early adopters. It was a long journey, and I rode alongside andbuilt applications on top of it during early alpha and beta phases. The final result of thatx

preface xijourney was Angular 2.0 (version 2.0 and above is known as just Angular), and its community has grown rapidly since its release.I started working on Angular in Action while Angular was still in early beta for version 2.0. Angular then underwent regular and rapid iterations during the book’s writing and development. But today Angular is stable and evolves with a well-defined releasecycle for new features and deprecations. The book examples are written to work withAngular 5 and above, and going forward, the GitHub projects will have notes about anyrequired changes to keep up with Angular’s evolution.

acknowledgmentsI’d like to thank first and foremost my wife, Linda, for her patience and understandingas I wrote this book, largely during the evening and weekend hours. I appreciate yoursupport, 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 Stergius and Cynthia Kane, technical developmental editor Alain Couniot, technical proofreader Tanya Wilke, and review editor Ivan Martinović. Several external reviewers alsoprovided helpful feedback on different stages of the manuscript: Harsh Raval, KumarUnnikrishnan, Michael A. Angelo, Phily Austria, Radoslaw Pilski, and Tony Brown.Along with that team were others at Manning who helped manage the cycle of earlyreleases and the final production release, including project editor Kevin Sullivan, copyeditor Corbin Collins, and proofreader Alyson Brener.A big thank you goes to the Angular team for creating Angular and also for the opportunities they’ve given me to talk with team members individually. Google also sponsorsthe Google Developer Experts program, which has a great list of Angular experts whohave been helpful and which I’m proud to belong to.I also want to thank Jason and David Aden for their early contributions and timeworking on the manuscript with me.Finally, thank you, the reader, for picking up this book to spend your precious timewith me between these pages. If it weren’t for you, I wouldn’t have a reason to write. Ihope to hear from you and see what you build!xii

about this bookAngular in Action is designed to help you learn how to use Angular in building yourown web applications. I’ve brought the core lessons from my own experiences intothis book. I’ve built a number of large enterprise applications on Angular and manysmaller ones as well. I believe similar best practices go into most well-written applications 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’sused to build web applications, and how to then ship those into production. This foundational knowledge will enable you to learn additional concepts more quickly and easily (often by reviewing the documentation or even blog posts).There are certainly more Angular topics than could be covered in a single book, asAngular is an ambitious and comprehensive set of tools and libraries. I took great careto make this a book that works on multiple levels. You may find some topics to be moreadvanced than you need right now, but you can always come back to them later. Or youmay find that the basics are familiar but the more advanced topics help fill in the gaps.Who should read this bookAlthough I believe Angular is accessible for developers, this book is targeted at readerswho have the subject knowledge detailed in the following list. Other readers will certainlyfind 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 littlebit of experience with building them.¡ JavaScript —You have enough knowledge of JavaScript and its syntax to be able tofollow along with the examples.¡ HTML/CSS —You understand the roles of HTML and CSS, as well as their syntax.xiii

xivabout this bookI mention some topics in the book that are important but not part of Angular. You mayknow nothing about some of these, but the book provides enough cursory knowledgethat you should be able to follow along:¡ TypeScript —Angular is written with TypeScript, and so are all the examples in thisbook. If you’re new to TypeScript, I provide many hints along the way, but I suggest you review the official documentation at www.typescriptlang.org.¡ Reactive programming —Angular’s design often allows and recommends usingreactive-style programming, which is usually used in conjunction with the popular RxJS library. There’s a lot of great material out there for learning reactive andRxJS, and I share a few links to it in the book.How this book is organizedThis book is divided into themed chapters, beginning with the core details of Angular and expanding into more complex themes. Chapters 1–3 lay the groundwork forunderstanding what Angular is (and isn’t) and discuss its role in building your applications. These chapters also provide a quick but fairly comprehensive tutorial of manyof Angular’s key features. If you’re already familiar with Angular, you may find thesesections 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 togetherfor more complex interactions. You can’t have an Angular application without components, and I cover them in great detail in these chapters so you can focus on otheraspects in the remainder of the book.Chapters 6–9 focus on key topics in building applications. Chapter 6 is all about services and, subsequently, dependency injection. Understanding how to manage yourservices is key to building a larger Angular application, and often key to using othercapabilities as well. Chapter 7 looks closely at the router and how to use it to createsimple to complex navigation patterns that are used in many web applications. Chapter8 shows you how to build your own custom directives and pipes, which become crucialwhen 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, aswell as how to create your own custom form controls.The last two chapters round off your Angular training with a focus on testing in chapter 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, butAngular provides some great tools that make it easy even for large enterprise applications to use. I suggest you use them too! The brief appendix discusses the transitionfrom AngularJS to Angular (or version 1.x to 2 ).If you’re brand new to Angular and want a guided tour, I recommend reading thechapters in order. This approach will give you incremental knowledge to build on asyou go, as often a chapter glosses over details that were covered in an earlier one.

about this bookxvIf 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 thatcover familiar material and then look more closely at later parts of a chapter to learnmore complex capabilities. As you skim, keep an eye out for diagrams that explain various concepts; they’re a great way to quickly validate whether you understand the topicat 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’llhave to follow along through the whole chapter. The final versions of the code are provided if you don’t want to follow the examples and build the code yourself, but I stronglyencourage you to code along. You’ll understand the coding and retain the information more effectively that way. If you run into any issues with a chapter example, youcan check the GitHub project for any potential code changes that were required afterthe 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 chapterexample code.About the codeAll 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 willalso 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, soyou don’t need to download everything ahead of time.You’ll need to have a recent version of NodeJS installed on your machine. Chapter 1 covers more specific things to install for the Angular CLI. You also need a modernbrowser—preferably one that has good debugging tools, like Chrome. If you’re running an outdated browser (like IE10), the code won’t run, so update your browser forcompatibility and security.This book contains many examples of source code, both in numbered listings andinline with normal text. In both cases, source code is formatted in a fixed-width fontlike this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a newfeature adds to an existing line of code.In many cases, the original source code, has been reformatted; we’ve added linebreaks 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 listings when the code is described in the text. Code annotations accompany many of thelistings, highlighting important concepts.Book forumPurchase of Angular in Action includes free access to a private web forum run byManning Publications where you can make comments about the book, ask technical

xviabout this bookquestions, and receive help from the author and from other users. To access the forum,go to n. You can also learnmore about Manning's forums and the rules of conduct at s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. Itis 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 tryasking the author some challenging questions lest his interest stray! The forum and thearchives of previous discussions will be accessible from the publisher’s website as long asthe book is in print.

about the authorJeremy Wilken is a software engineer with a passion for designing applications andtechnology solutions that focus on improving the lives of users. He is a Google Developer Expert for Web Technologies and Angular as well as the Google Assistant, whichis an endorsement from Google as a subject matter expert and community leader inAngular and the web.Most of his day-to-day work is in building Angular applications, but he also spendsa lot of time and energy speaking at events, running workshops and trainings, writing, and helping build community through meetups and conferences. He’s worked forcompanies 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.xvii

about the cover illustrationThe figure on the cover of Angular in Action is captioned “A colonel of the Strelitzes, theold Russian militia and body guard to the czars of Moscovy.” The illustration is takenfrom 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 thatthese are hand-colored copperplate engravings, heightened with gum arabic.Thomas Jefferys (1719–1771) was called “Geographer to King George III.” He wasan English cartographer who was the leading map supplier of his day. He engraved andprinted maps for government and other official bodies and produced a wide range ofcommercial maps and atlases, especially of North America. His work as a map makersparked an interest in local dress customs of the lands he surveyed and mapped, whichare brilliantly displayed in this collection. Fascination with faraway lands and travel forpleasure were relatively new phenomena in the late eighteenth century, and collectionssuch as this one were popular, introducing both the tourist as well as the armchair traveler to the inhabitants of other countries.The diversity of the drawings in Jefferys’ volumes speaks vividly of the uniquenessand individuality of the world’s nations some 200 years ago. Dress codes have changedsince 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, trying to view it optimistically, we’ve traded a cultural and visual diversity for a more variedpersonal 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 celebrates the inventiveness and initiative of the computer business with book covers basedon the rich diversity of regional life of two centuries ago, brought back to life by Jefferys’pictures.xviii

1Angular: a modernweb platformThis chapter covers¡ Angular as a platform for modern applications¡ Key reasons for choosing Angular¡ Angular’s architecture and how componentsform the basis of it¡ How AngularJS differs from Angular¡ ES2015 and TypeScript and how Angularuses themAngular is a modern web application platform that promises to provide developerswith a comprehensive set of tools and capabilities to build large, robust applications.The core value proposition of Angular is to make it possible to build applicationsthat work for nearly any platform—whether mobile, web, or desktop. The Angularteam has focused on building much more than a robust application framework;they’ve also built an entire ecosystem.All that’s a bit of a mouthful, which is partly what makes Angular such an excitingtechnology to work with. Let’s start by taking a closer look at why you would chooseAngular for your next project.1

21.1Chapter 1 Angular: a modern web platformWhy choose Angular?Building web applications that can meet the needs of users is not a trivial task. Thequality and complexity of applications is ever increasing, and so are users’ expectationsfor quality and capabilities. Angular exists to help developers deliver applications tomeet these demands.If you haven’t settled on Angular as a tool of choice yet, let’s quickly cover some ofthe top reasons that you should seriously consider Angular. Some items are coveredmore in section 1.3, but here are the top highlights in my experience:¡ Inspired by web standards, enhanced by modern capabilities —Anyone building webapplications today knows there are many different ways and ideas about howto design applications. Angular tries to design its framework and the development process around common standards (like leveraging the latest JavaScriptlanguage features), using modern capabilities (such as embracing TypeScript fortype enforcement).¡ Development tooling included, customizations available —Angular provides a commondeveloper experience through its CLI tooling (for generating, building, testing,and deploying apps), while making those same tools available to be easily integrated into custom solutions (such as a custom build toolchain) and third-partytools (like different editors or IDEs).¡ Powerful ecosystem with a large community —There is an ever-growing number ofthird-party libraries, UI libraries, blog posts, and events. Angular’s large andactive community provides a great foundation on which to learn and shouldinstill confidence that it will remain a valuable technology.¡ Sponsored by Google, open source community driven —Google has a team of engineers,managers, and evangelists solely dedicated to bringing Angular to the rest ofGoogle and the entire web community. With thousands of “internal customers”who rely on Angular inside Google, the Angular team uses those experiences toinform future development and receives large volumes of external contributionsthat together shape Angular’s future (you can join in too!).Angular is much more than just a JavaScript library that powers some of the top websites in the world. I’m passionate about open source communities, and I’m an advocatefor people to get engaged in a project as part of their regular routine. Projects in theAngular community are where I put a lot of my energy and contributions, and I inviteyou to join me. Although I do engage with the Angular project itself, I primarily contribute to projects in the Angular ecosystem, such as Clarity, a UI component libraryand design language.You may be a developer trying to figure out whether Angular will meet your needs, oryou may be a manager trying to understand the role of the technology, or trying to figure out how to improve your current applications. Regardless of where you’re startingfrom, the Angular ecosystem has a lot to offer.

What you’ll learn1.23What you’ll learnThis book is designed to be a comprehensive walk through Angular, but it’s also meantto get you informed about various aspects of the ecosystem. The approach is alwaysexperiential, where you’ll learn about a topic and build it yourself to see the conceptscome to life. At the end of this book you should be able to make high-quality Angularapplications and have the foundational knowledge and experience on which to build acareer and applications.The key takeaways in this book include the following:¡ How Angular works —We’ll look at some of the key internal concepts that make itsuch a compelling platform for building your applications. You’ll learn the concepts and build examples to illustrate them as part of a functional application.¡ How to build applications —In most chapters, we’ll walk step-by-step through anumber of real-life examples. The code examples are comprehensive and focuson a certain set of goals for each chapter.¡ Learn about the ecosystem —Each example uses some third-party libraries and capabilities. This helps you see more of a realistic development experience and gain afoundation for building your own applications.¡ Get practical insights from my experiences —In many of the examples and notes aboutthem, I share practical advice from my experience, including suggestions onthings to avoid (even if it's perfectly legitimate code) and how to choose betweendifferent approaches when they’re provided.You should be equipped to design and build web applications with Angular by the endof the book. If you’re not as interested in the technical aspects (perhaps as a manager),you’ll still glean a lot of the same lessons to get a solid frame of reference for howAngular works and what it provides for your project.There are a few things I won’t be able to cover in this book, but just because theseitems aren’t specifically discussed, it doesn’t mean you can’t learn many things relatedto them. The following are not core topics covered in this book:¡ How to write libraries

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.