Learning Angular: A practical guide to building web applications with modern Angular, 5th Edition / Изучаем Angular: Практическое руководство по созданию веб-приложений с использованием современного Angular, 5-е издание Год издания: 2024 Автор: Bampakos Aristeidis / Бампакос Аристейдис Издательство: Packt Publishing ISBN: 978-1-83508-748-0 Серия: Expert Insight Язык: Английский Формат: PDF/EPUB Качество: Издательский макет или текст (eBook) Интерактивное оглавление: Да Количество страниц: 487 Описание: Learn frontend development the Angular way – build your first production-grade web applications from scratch in Angular with the help of expert guidance and step-by-step explanations. Key Features Explore the basics of Angular development, from components and templates to forms, routing, and services Get up to speed with the new paradigms modern Angular brings, including standalone APIs, new control flow syntax, Signals, and server-side rendering (SSR) Discover best practices for building, deploying, debugging, and testing Angular applications Book Description Angular is an extremely fast, cross-platform JavaScript framework loved by millions. Learning Angular is a comprehensive introduction to the framework from an experienced Angular developer and Google Developer Expert. You’ll learn the Angular way of development as you build a real-world app from the ground up. Updated for Angular 19, this fifth edition tackles landmark changes in Angular after the “Angular Renaissance”. It covers app creation with standalone components, Angular Signals, and the new control flow syntax, while acknowledging differences in approach in older Angular code. You’ll also find a brand-new chapter on optimizing performance with SSR and hydration, as well as revamped content on TypeScript. Angular developers of all experience levels will benefit from this book. It is especially useful if you are new to Angular, as it will help you get to grips with the bare bones of the framework. By the end of this book, you’ll be able to create Angular applications with TypeScript from scratch and apply best practices in any Angular codebase. What you will learn Use the Angular CLI to scaffold, build, and deploy new Angular applications Create Angular applications using standalone APIs Build rich components with Angular template syntax Apply reactivity patterns with the RxJS library and Signals Craft beautiful user interfaces using Angular Material Create HTTP data services to access APIs and provide data to components Improve your debugging and error handling skills during runtime and development Optimize application performance with SSR and hydration techniques Who this book is for This book is for JavaScript developers and web developers dipping their feet for the first time in the world of frontend development with Angular, as well as those migrating to the Angular framework to build professional web applications. Current Angular developers looking to catch up with modern Angular will also find this book useful. You’ll need prior exposure to JavaScript and a solid foundation in the basics of web programming before you get started with this book. Научитесь разрабатывать интерфейсы с помощью Angular – создавайте свои первые веб-приложения производственного уровня с нуля в Angular с помощью экспертных рекомендаций и пошаговых объяснений. Основные характеристики Изучите основы разработки на Angular, от компонентов и шаблонов до форм, маршрутизации и сервисов Ознакомьтесь с новыми парадигмами, которые предлагает современный Angular, включая автономные API, новый синтаксис потока управления, сигналы и рендеринг на стороне сервера (SSR) Ознакомьтесь с лучшими практиками создания, развертывания, отладки и тестирования приложений Angular Описание книги Angular - это чрезвычайно быстрый кроссплатформенный JavaScript-фреймворк, который любят миллионы людей. Изучение Angular - это всестороннее знакомство с фреймворком от опытного разработчика Angular и эксперта Google Developer. Вы познакомитесь с методикой разработки на Angular по мере создания реального приложения с нуля. Это пятое издание, обновленное для версии Angular 19, посвящено важным изменениям в Angular после “ренессанса Angular”. В нем рассказывается о создании приложений с использованием автономных компонентов, сигналов Angular и нового синтаксиса потока управления, при этом учитываются различия в подходах к более старому коду Angular. Вы также найдете совершенно новую главу об оптимизации производительности с помощью SSR и гидратации, а также обновленный контент на TypeScript. Эта книга будет полезна разработчикам Angular с любым уровнем опыта. Она особенно полезна, если вы новичок в Angular, поскольку поможет вам разобраться с основными принципами работы фреймворка. К концу этой книги вы сможете создавать приложения Angular с помощью TypeScript с нуля и применять лучшие практики в любой кодовой базе Angular. Чему вы научитесь Используйте интерфейс командной строки Angular для создания, компоновки и развертывания новых приложений Angular Создавайте приложения Angular с использованием автономных API Создавайте богатые компоненты с помощью синтаксиса шаблона Angular Применяйте шаблоны реактивности с помощью библиотеки RxJS и сигналов Создавайте красивые пользовательские интерфейсы с использованием Angular Material Создавайте службы передачи данных HTTP для доступа к API и предоставления данных компонентам Совершенствуйте свои навыки отладки и обработки ошибок во время выполнения и разработки Оптимизируйте производительность приложений с помощью методов SSR и гидратации Для кого предназначена эта книга Эта книга предназначена для разработчиков JavaScript и веб-сайтов, которые впервые знакомятся с миром разработки интерфейсов с помощью Angular, а также для тех, кто переходит на платформу Angular для создания профессиональных веб-приложений. Нынешние разработчики Angular, стремящиеся освоить современный Angular, также найдут эту книгу полезной. Прежде чем приступить к работе с этой книгой, вам потребуется предварительное знакомство с JavaScript и прочные основы веб-программирования.
Примеры страниц (скриншоты)
Оглавление
Preface xix Chapter 1: Building Your First Angular Application 1 Technical requirements ...................................................................................................... 2 What is Angular? ................................................................................................................. 2 Why choose Angular? .......................................................................................................... 4 Cross-platform • 4 Tooling • 4 Onboarding • 5 The usage of Angular worldwide • 5 Setting up the Angular CLI workspace ................................................................................ 6 Prerequisites • 6 Node.js • 6 npm • 7 Git • 7 Installing the Angular CLI • 7 CLI commands • 8 Creating a new project • 9 The structure of an Angular application ........................................................................... 12 Components • 13 Bootstrapping • 13 Template syntax • 14 Angular tooling ................................................................................................................. 16 Angular DevTools • 16 VSCode Debugger • 20 VSCode Profiles • 22 Angular Language Service • 22 Material Icon Theme • 24 EditorConfig • 24 Summary .......................................................................................................................... 25 Chapter 2: Introduction to TypeScript 27 Technical requirements .................................................................................................... 27 JavaScript essentials ......................................................................................................... 28 Variable declaration • 28 Function parameters • 31 Arrow functions • 32 Optional chaining • 33 Nullish coalescing • 34 Classes • 35 Modules • 36 What is TypeScript? .......................................................................................................... 37 Getting started with TypeScript ....................................................................................... 39 Types • 41 String • 42 Boolean • 42 Number • 42 Array • 42 any • 43 Custom types • 43 Functions • 44 Classes • 45 Interfaces • 48 Generics • 50 Utility types • 52 Summary • 52 Chapter 3: Structuring User Interfaces with Components 55 Technical requirements .................................................................................................... 55 Creating our first component ............................................................................................ 56 The structure of an Angular component • 56 Creating components with the Angular CLI • 58 Interacting with the template ........................................................................................... 60 Loading the component template • 60 Displaying data from the component class • 62 Controlling data representation • 63 Class binding • 71 Style binding • 72 Getting data from the template • 73 Component inter-communication .................................................................................... 75 Passing data using an input binding • 75 Listening for events using an output binding • 77 Emitting data through custom events • 80 Local reference variables in templates • 81 Encapsulating CSS styling ................................................................................................. 82 Deciding on a change detection strategy .......................................................................... 85 Introducing the component lifecycle ................................................................................ 89 Performing component initialization • 90 Cleaning up component resources • 91 Detecting input binding changes • 93 Accessing child components • 95 Summary .......................................................................................................................... 96 Chapter 4: Enriching Applications Using Pipes and Directives 99 Technical requirements .................................................................................................... 99 Manipulating data with pipes ........................................................................................... 99 Building pipes ................................................................................................................. 106 Sorting data using pipes • 106 Passing parameters to pipes • 110 Change detection with pipes • 112 Building directives ........................................................................................................... 113 Displaying dynamic data • 114 Property binding and responding to events • 118 Summary ........................................................................................................................ 120 Chapter 5: Managing Complex Tasks with Services 121 Technical requirements ................................................................................................... 122 Introducing Angular DI .................................................................................................... 122 Creating our first Angular service .................................................................................... 124 Injecting services in the constructor • 126 The inject keyword • 128 Providing dependencies across the application ............................................................... 129 Injecting services in the component tree ......................................................................... 133 Sharing dependencies through components • 133 Root and component injectors • 138 Sandboxing components with multiple instances • 139 Restricting provider lookup • 145 Overriding providers in the injector hierarchy ................................................................. 147 Overriding service implementation • 147 Providing services conditionally • 149 Transforming objects in Angular services • 151 Summary ......................................................................................................................... 153 Chapter 6: Reactive Patterns in Angular 155 Technical requirements ................................................................................................... 155 Strategies for handling asynchronous information .......................................................... 156 Shifting from callback hell to promises • 156 Observables in a nutshell • 160 Reactive programming in Angular ................................................................................... 162 The RxJS library ............................................................................................................... 165 Creating observables • 166 Transforming observables • 167 Subscribing to observables .............................................................................................. 169 Unsubscribing from observables ...................................................................................... 172 Destroying a component • 172 Using the async pipe • 174 Summary ......................................................................................................................... 176 Chapter 7: Tracking Application State with Signals 177 Technical requirements ................................................................................................... 177 Understanding signals .................................................................................................... 178 Reading and writing signals ............................................................................................ 178 Computed signals ........................................................................................................... 180 Cooperating with RxJS .................................................................................................... 182 Summary ......................................................................................................................... 185 Chapter 8: Communicating with Data Services over HTTP 187 Technical requirements ................................................................................................... 187 Communicating data over HTTP ..................................................................................... 188 Introducing the Angular HTTP client .............................................................................. 189 Setting up a backend API ................................................................................................. 191 Handling CRUD data in Angular ...................................................................................... 192 Fetching data through HTTP • 192 Modifying data through HTTP • 202 Adding new products • 203 Updating product price • 207 Removing a product • 210 Authentication and authorization with HTTP ................................................................. 214 Authenticating with a backend API • 214 Authorizing user access • 216 Authorizing HTTP requests • 218 Summary ........................................................................................................................ 222 Chapter 9: Navigating through Applications with Routing 223 Technical requirements .................................................................................................. 224 Introducing the Angular router ....................................................................................... 224 Specifying a base path • 226 Enabling routing in Angular applications • 226 Configuring the router • 227 Rendering components • 228 Configuring the main routes ........................................................................................... 228 Organizing application routes ........................................................................................ 232 Navigating imperatively to a route • 233 Using built-in route paths • 238 Styling router links • 239 Passing parameters to routes .......................................................................................... 240 Building a detail page using route parameters • 240 Reusing components using child routes • 245 Taking a snapshot of route parameters • 247 Filtering data using query parameters • 248 Binding input properties to routes • 250 Enhancing navigation with advanced features ............................................................... 252 Controlling route access • 252 Preventing navigation away from a route • 254 Prefetching route data • 256 Lazy-loading parts of the application • 259 Protecting a lazy-loaded route • 262 Summary ........................................................................................................................ 263 Chapter 10: Collecting User Data with Forms 265 Technical requirements .................................................................................................. 265 Introducing web forms ................................................................................................... 265 Building template-driven forms ..................................................................................... 267 Building reactive forms .................................................................................................... 271 Interacting with reactive forms • 271 Creating nesting form hierarchies • 276 Modifying forms dynamically • 278 Using a form builder • 285 Validating input in forms ................................................................................................ 288 Global validation with CSS • 288 Validation in template-driven forms • 290 Validation in reactive forms • 294 Building custom validators • 297 Manipulating form state ................................................................................................. 303 Updating form state • 303 Reacting to state changes • 304 Summary ........................................................................................................................ 306 Join Us on Discord ........................................................................................................... 306 Chapter 11: Handling Application Errors 307 Technical requirements .................................................................................................. 307 Handling runtime errors ................................................................................................. 308 Catching HTTP request errors • 308 Creating a global error handler • 312 Responding to the 401 Unauthorized error • 315 Demystifying framework errors ....................................................................................... 316 Summary ........................................................................................................................ 318 Chapter 12: Introduction to Angular Material 319 Technical requirements ................................................................................................... 319 Introducing Material Design ........................................................................................... 320 Introducing Angular Material ......................................................................................... 320 Installing Angular Material • 321 Adding UI components • 324 Theming UI components • 325 Integrating UI components ............................................................................................. 329 Form controls • 330 Input • 330 Select • 335 Chips • 337 Navigation • 338 Layout • 340 Card • 341 Data table • 344 Popups and overlays • 350 Creating a confirmation dialog • 350 Configuring dialogs • 353 Getting data from dialogs • 354 Displaying user notifications • 355 Summary ........................................................................................................................ 359 Chapter 13: Unit Testing Angular Applications 361 Technical requirements .................................................................................................. 362 Why do we need unit tests? ............................................................................................. 362 The anatomy of a unit test .............................................................................................. 363 Introducing unit tests in Angular .................................................................................... 365 Testing components ........................................................................................................ 366 Testing with dependencies • 370 Replacing the dependency with a stub • 371 Spying on the dependency method • 375 Testing asynchronous services • 378 Testing with inputs and outputs • 380 Testing with a component harness • 383 Testing services ............................................................................................................... 385 Testing synchronous/asynchronous methods • 386 Testing services with dependencies • 387 Testing pipes ................................................................................................................... 389 Testing directives ............................................................................................................ 390 Testing forms .................................................................................................................. 392 Testing the router ........................................................................................................... 395 Routed and routing components • 395 Guards • 398 Resolvers • 401 Summary ........................................................................................................................ 403 Chapter 14: Bringing Applications to Production 405 Technical requirements .................................................................................................. 406 Building an Angular application ..................................................................................... 406 Building for different environments • 408 Building for the window object • 410 Limiting the application bundle size ............................................................................... 411 Optimizing the application bundle ................................................................................. 412 Deploying an Angular application ................................................................................... 415 Summary ........................................................................................................................ 416 Chapter 15: Optimizing Application Performance 417 Technical requirements .................................................................................................. 418 Introducing Core Web Vitals ........................................................................................... 418 Rendering SSR applications ............................................................................................ 422 Overriding SSR in Angular applications • 425 Optimizing image loading .............................................................................................. 428 Deferring components .................................................................................................... 430 Introducing deferrable views • 430 Using deferrable blocks • 431 Loading patterns in @defer blocks • 437 Prerendering SSG applications ........................................................................................ 440 Summary ....................................................................................................................... 441 Other Books You May Enjoy 445 Index 449
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum