Statistics
20
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-19
Support
Share

AuthorArmen Vardanyan

Discover the new features and techniques of the most modern versions of Angular. The powerful Angular framework is ever-evolving, with each new iteration bringing amazing new modern features. Modern Angular gets you rapidly up to speed with Angular’s latest innovations. Inside Modern Angular you’ll learn how to: • Create modern Angular apps with the newest framework capabilities • Setting up and structuring your Angular projects • Implement advanced testing strategies for Angular • Benefit from new improvements in debugging, image loading, and component inputs

Tags
No tags
Publisher: Manning Publications
Publish Year: 2024
Language: 英文
Pages: 306
File Format: PDF
File Size: 12.0 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

M A N N I N G Armen Vardanyan Also covers signals, standalone, SSR, zoneless, and more
The process of integration of new features into Angular An idea arrives The idea is explored. An RFC document is compiled. The draft is initially shared internally. The draft is reviewed. The RFC goes public. Comments and feedback are gathered. The feature is added into a release. If the change is too revolutionary, the feature is marked as developer preview. If the feature is successful, it is marked as stable. Either as a GitHub issue or an idea from the team itself The Angular team privately experiments with it and finds viable implementations. Core team members and Google Developer experts will read it first. Now the wider community can add feedback. A request for comments doc will detail the changes, motivations, and a draft API. The core team discourages the developers from using the feature in production codebases, instead expecting developers to “play” with it. Usually developer preview features appear in major releases.
Modern Angular ALSO COVERS SIGNALS, STANDALONE, SSR, ZONELESS, AND MORE ARMEN VARDANYAN 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 ©2025 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. The authors and publisher have made every effort to ensure that the information in this book was correct at press time. The authors and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Ian Hough 20 Baldwin Road Technical editor: Santosh Lalchand Yadav PO Box 761 Review editor: Dunja Nikitović Shelter Island, NY 11964 Production editor: Deirdre Blanchfield-Hiam Copy editor: Kari Lucke Proofreader: Keri Hales Technical proofreader: Tanya Wilke Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781633436923 Printed in the United States of America
Dedicated to my sister, Marina, who bought for me all my laptops except the one I used to write this book
contents preface x acknowledgments xii about this book xiv about the author xvii about the cover illustration xviii 1 Welcome to modern Angular 1 1.1 What to expect 2 Who will benefit from reading this book? 2 ■ What do we need to know before getting started? 2 ■ How is the book structured? 3 1.2 How Angular was 3 Angular’s core features 4 ■ What is an Angular application? 5 1.3 Let’s start a modern Angular app 7 Using the Angular CLI 7 ■ Creating a new project 8 What changed? 9 1.4 What’s new in Angular? 11 How does Angular evolve? 11 ■ How does Angular recognize problems? 12 ■ Current goals 13 ■ New features 14 What about the future? 16 ■ The learning process 18iv
CONTENTS v2 A standalone future 19 2.1 Why abandon NgModules? 20 Hard to learn, hard to explain 20 ■ Indirectness and boilerplate 22 ■ Other concerns with NgModules 24 2.2 Previous solutions 24 Hierarchic shared modules 25 ■ Enter SCAMs 25 2.3 Developing apps without NgModules 27 Creating our first standalone component 27 ■ Routing standalone components and providing dependencies 31 2.4 Lazy-loading components 34 Lazy-loading with NgModules 34 ■ Lazy-loading a single standalone component 35 ■ Lazy-loading several standalone components 36 ■ Providing dependencies only to certain routes 38 ■ Lazy-loading a component into another component 39 2.5 Migrations and common pitfalls 42 Migrating by hand 42 ■ Using SCAMs 43 ■ Migrating with a schematic command 43 ■ Handling circular dependencies 45 2.6 Exercises for the reader 46 3 Revitalized dependency injection 47 3.1 How does dependency injection work? 48 Why do we need DI? 48 ■ Let’s build a primitive DI mechanism 49 ■ Dependency injection the Angular way 50 Injection contexts 54 3.2 The inject function 55 Another way of injecting dependencies 55 ■ Injecting dependencies outside classes 56 ■ Why we should always use inject 58 What about the drawbacks? 61 3.3 Functional guards, resolvers, and interceptors 62 Building an AuthGuard 62 ■ Building an EmployeeResolver 64 Adding tokens to HTTP requests 66 ■ Migrating to functional guards/resolvers/interceptors 67 3.4 DI deep dive 68 DI lookup and how to modify it 69 ■ Truncating text with DI 70 3.5 Exercises for the reader 72
CONTENTSvi4 New capabilities of Angular building blocks 74 4.1 Powerful inputs 75 Required inputs 75 ■ Transforming input values 78 Binding routing parameters to input properties 81 Inputs for dynamic components 83 4.2 Host directives 88 Extending existing directives 88 ■ Using multiple directives and adding inputs 89 ■ Things to know when using host directives 90 4.3 Type-safe reactive forms 92 Downsides of using untyped forms 92 ■ Introducing type-safe forms 93 ■ Common pitfalls when working with type-safe forms 94 ■ Migrating to type-safe forms 95 ■ Form events 95 4.4 NgOptimizedImage 96 Adding lazy loading and remembering to set width/height 97 Prioritizing image loading 98 ■ Srcsets and image loaders 98 4.5 Other improvements 100 Self-closing component tags 100 ■ Fetch-based HttpClient 100 Support for default export components in routing 101 ■ Improved error messages 101 4.6 Exercises for the reader 102 5 RxJS in modern Angular 103 5.1 What is reactive programming? 104 5.2 Why we (still) need RxJS 105 5.3 Unsubscribing from observables 106 Why unsubscribe? 107 ■ Problems with unsubscribing 107 Introducing DestroyRef 108 ■ The takeUntilDestroyed operator 111 5.4 Writing our own custom RxJS operators 115 What is an RxJS operator? 115 ■ How do operators work? 117 Building custom operators 119 5.5 Exercises for the reader 124 6 Signals: A new approach to reactive programming 125 6.1 Why go beyond RxJS? 126 What are the problems with RxJS? 126 ■ What must the solution look like? 129
CONTENTS vii6.2 What is a signal? 130 Creating signals 131 ■ Updating signals 132 ■ Creating signals vs. observables 134 6.3 Building Angular components with signals 134 Creating TimeOffComponent 135 ■ Handling signals in Angular components 137 6.4 Computed signals 138 Creating computed signals 138 ■ Simplifying complex logic in Angular components using computed signals 140 6.5 Effects 143 Creating effects 143 ■ Important things to know about effects 144 ■ When to use effects 146 6.6 RxJS and signals interoperability 147 Converting observables to signals 147 ■ Converting signals to observables 149 6.7 Exercises for the reader 151 7 Signals: A deep dive 152 7.1 Advanced options when dealing with signals 152 Signal equality 153 ■ Untracking dependencies 154 Manual cleanup 156 ■ Readonly signals and synchronizing with RxJS 158 7.2 Signals under the hood 159 The nature of signals 159 ■ How changes to signals propagate 160 7.3 State management with signals 163 State management: The task 163 ■ State management: The implementation 164 ■ State management: The problems 167 Advanced interoperability with RxJS 170 7.4 Migrating to signals 173 Migrating RxJS-heavy Angular applications 173 ■ Migrating more traditional Angular applications 174 7.5 The future of signals 175 Signal-based components 175 ■ Signal inputs and outputs 175 Everything else 176 7.6 Exercises for the reader 176
CONTENTSviii8 Unit testing in modern Angular 178 8.1 Unit testing: The what and the why 179 Prerequisites 179 ■ What is a unit test? 179 ■ Why do we want unit tests? 180 8.2 Configuring a testing environment 181 Choosing a test runner 181 ■ Setting up the test runner 182 Installing third-party tools 185 8.3 Running Angular unit tests 186 What do unit tests look like? 186 ■ Providing mock dependencies 188 ■ Testing components 190 ■ Testing services 194 ■ Testing signals 197 8.4 Powers of AI with Angular unit tests 204 Unit testing Angular applications with ChatGPT 204 Unit testing Angular applications with GitHub Copilot 208 8.5 The future of unit testing in Angular 209 8.6 Exercises for the reader 210 9 Modern Angular everywhere 211 9.1 What is server-side rendering? 212 SSR: The what 212 ■ SSR: The why 214 SSR: The how 216 9.2 Building Angular apps with SSR from scratch 218 How is an SSR Angular application different from a SPA? 218 Running an SSR Angular application 221 ■ Building components in an SSR Angular application 223 9.3 Improving Angular SSR 228 HTTP caching 228 ■ Client-side hydration 231 Prerendering 233 9.4 Building an Angular application 235 What does building an Angular application mean? 235 ESBuild and Vite 236 ■ Configuring environments for Angular applications 236 ■ Preparing to deploy Angular applications 238 9.5 Exercises for the reader 240
CONTENTS ix10 What’s next in modern Angular? 241 10.1 New template syntax 241 Goodbye ngIf! 242 ■ Hello @for! 246 ■ @switch 249 Migrating to the new template syntax 251 10.2 Deferrable views 252 Deferring a simple component 252 ■ Deferring depending on a condition or trigger 254 ■ Customizing deferred loading 257 10.3 Zoneless Angular applications 259 How change detection works in Angular 259 ■ Why change detection in Angular needs to improve 262 ChangeDetectionStrategy.OnPush 263 ■ Introducing granular change detection 265 ■ Zoneless scheduler for change detection 273 10.4 In other news 275 index 277
preface When I started my career in the spring of 2016, Angular, as we know it today, did not yet exist; instead, I used to be an Angular.js developer—a long-forgotten framework that has now reached its end of life. While it offered interesting features and an opportunity to build more organized web apps, it did have some glaring flaws. This brings us to September 2016, when Angular 2 or, as it is known now, simply Angular was released. This was huge! Everything changed at a moment’s notice: we now had TypeScript, classes everywhere, strict organizational rules, and, soon enough, even a dedicated CLI tool to manage over applications. Of course, this was overwhelming at first; how- ever, upon further research, it was revealed that the framework is actually very solid and an immediate upgrade upon anything we had prior, and that was the moment when many frontend developers, including myself, fell in love with it. Of course, this new Angular, like any other tool, wasn’t without flaws either: so began the process of continuous improvements upon the framework that we know and love. In the few first versions the framework stabilized, then in versions 8 and 9, we got a new rendering engine, and now we get a new phase of massive improvements that are often referred to (even by the Angular core team itself) as the “Angular renaissance.” I was always very involved with the progress and in-depth characteristics of Angular in the sense of documenting them. I loved going to the Angular source code and trying to figure out how the most interesting features actually work, trying out the most chal- lenging problems, and speaking to industry experts. What I discovered is that, for me,x
PREFACE xithe best way to learn something is to write about it. I started writing articles about Angular, going to podcasts, and in 2019 even began public speaking. All of this in the end culminated in this book. But why have this book at all? Well, when this first began, we as a community didn’t know anything about the “Angular renaissance”—we just knew Angular had sched- uled major releases every six months, and with every release, we got some small new interesting things. However, we noticed that the changes incrementally got more and more revolutionary, so to speak; it was useful to write articles about all the features or talk about them at podcasts and events, but it kept growing and growing, with more changes that necessitated a very thorough exploration. Then it became obvious that something more was necessary. And that is how this book came to be: a book that is meant to help Angular devel- opers who are excited about these new changes, or maybe frightened by them, to understand the new features, appreciate them, use them in their new projects, or even migrate older projects toward a more modern approach. The book cannot possibly claim to be a complete guide to everything new in Angu- lar; as I write these words, Angular keeps changing and growing. During the writing of the book, I had to go back and change some things that were no longer current; this is the nature of software development, and the only thing we can do is keep learning. I know I learned a lot while writing this book, and I hope it will help you learn a thing or two about modern Angular too.
acknowledgments This book is a huge achievement for me, and there are lots of people who helped me, in different ways and forms, to accomplish it and who deserve this gratitude. First, I want to thank my girlfriend Shahane, who helped and supported me throughout this huge endeavor. Next, I would love to acknowledge my editors: development editor Ian Hough and technical editor Santosh Yadav. Ian did a tremendous job and helped me establish myself as a writer. Santosh was a huge inspiration for me for years before I even under- took writing a book and is probably the person with the most significant effect on my professional career ever. Thanks as well to all the people who worked on the pro- duction and promotion of this book at Manning—my copyeditor Kari Lucke, project editor Deirdre Blanchfield-Hiam, as well as the rest of the team—working with all of you was a delightful experience! I also want to acknowledge my friend Lars Gyrup Brink Nielsen for encouraging me to write a book, serving as a big inspiration, and helping in the initial stages of writing, as well as my colleagues Nune and Arsen, for helping me grow professionally and being so enthusiastic about the book. Of course, I must thank the entirety of the Angular core team and everyone who loves and contributes to our favorite framework. Finally, thanks to all the reviewers: Al Pezewski, Andy Robinson, Anooplal Hariha- ran, Aurélien Marocco, Betsegaw Lemma Amersho, Daniel McAlister, Dieter Jordens, Duncan McRae, Enrique Carro García, Eric Anderson, Frantisek Krul, Giuseppe Catalano Javid Asgarov, Jeff Smith, Juan Luis Barreda, Junaid Ramzan, Kiranxii
ACKNOWLEDGMENTS xiiiKrishnamurthy, Krishna Chaitanya Anipindi, Matteo Battista, Mitchell Fox, Peter Szabo, Rob Monhemius, Rodney A. James, Samuel Bosch, Simon Verhoeven, Steven Edwards, Tan Wee, and Tony Sweets. Your suggestions helped make this a better book.
about this book Modern Angular is here to help understand and embrace the most recent changes to the Angular ecosystem, (starting from v12 up to v17), to either build new Angular applications from scratch or to migrate existing apps to these new versions. It does not function as a tutorial for Angular as a whole but rather helps Angular developers gain concrete knowledge about the new features while diving a little deeper into the base knowledge whenever necessary Who should read this book Modern Angular is meant to be utilized by people who are already familiar with Angu- lar and have worked on projects before; it is good both for developers who just learned the important basics of the framework and those already very experienced with it. Additionally, it is useful to developers who maintain large legacy projects and look for strategies to bring their code up to modern standards. How this book is organized: A road map The book consists of 10 chapters, each covering a set of distinct new features. Each chapter first explores the old approach of doing things, then dives into the new approach by utilizing it in a brand-new project, and finally shows ways and strategies to help migrate existing codebases.  Chapter 1 discusses modern Angular as a whole, why the changes are happen- ing, how to set up a project from scratch using the recent Angular versions, and what structure these new projects have.xiv
ABOUT THIS BOOK xv Chapter 2 discusses standalone Angular building blocks, why we want them, how to perform all common tasks with standalone components, and how to migrate module-based components to become standalone.  Chapter 3 dives into Angular’s dependency injection mechanism, discusses the inject function, how it changed developers’ approaches to dependency injec- tion, and what building blocks were affected by this change.  Chapter 4 explores various small new additions and improvements, like the opti- mized image loader, improved component inputs, better debugging options, and more.  Chapter 5 discusses RxJS and how it works with Angular as of now and the new built-in interoperability library, tying in dependency injection improvements from chapter 3 to new approaches with RxJS.  Chapter 6 introduces signals, explains why they are necessary, and provides high-level knowledge about all of their features.  Chapter 7 dives deep into signals, explaining how they can improve application performance and how to approach some advanced tasks like state management and RxJS interoperability with them.  Chapter 8 discusses unit testing in modern Angular applications and some new useful tools that can help with the task.  Chapter 9 talks about server-side rendering, how it can enhance application performance, and how to build applications that utilize service-side rendering and web page prerendering.  Chapter 10 discusses future prospects of the Angular framework like zoneless change detection and completely signal-based applications, and also explores some experimental new features that are already available like the new template syntax and deferred loading of components. Readers are expected to read the book from start to end; however, after reading the first two chapters, developers can feel free to read the chapters on topics that interest them the most. About the code This book contains many examples of source code both in numbered listings and in line 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
ABOUT THIS BOOKxvifrom the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. Please note: in chapter 10, we take a different route by exploring some experimen- tal features on the code we already built; to have access to both versions, readers can use the source code repository and switch to the branch named “chapter-10” to review the other version. The complete code for the examples in the book is available for download from the Manning website at https://www.manning.com/books/modern-angular, and from GitHub at https://github.com/Armenvardanyan95/modern-angular-hrms. liveBook discussion forum Purchase of Modern Angular includes free access to liveBook, Manning’s online read- ing platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/modern -angular/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion. Manning’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. 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 sug- gest 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.
about the author ARMEN VARDANYAN is a Google Developer Expert for Angular and a frontend team lead with eight years of experience. He writes articles about Angular, TypeScript, RxJS, NgRx, and other related technologies and sometimes appears as a speaker at conferences. xvii
about the cover illustration The figure on the cover of Modern Angular, “Jeune Fille Armenienne,” or “Young Arme- nian girl,” is taken from a four-volume set by Auguste Wahlen, published in 1843. In those days, it was easy to identify where people lived and what their trade or sta- tion in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional cul- ture centuries ago, brought back to life by pictures from collections such as this one.xviii
The above is a preview of the first 20 pages. Register to read the complete e-book.