Angular for Enterprise Applications - Doguhan Uluca - E-Book

Angular for Enterprise Applications E-Book

Doguhan Uluca

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

If you’re looking to upskill and build sophisticated, minimalist web applications suited for enterprise use, Angular for Enterprise Applications is your guide to the next level of engineering mastery.
In its third edition, this Angular book distils hard-earned lessons into a lucid roadmap for success. Adopting a pragmatic approach founded on a robust technical base, you'll utilize both JavaScript and TypeScript fundamentals. You'll also embrace agile engineering coding principles and learn to architect optimally sized enterprise solutions employing the freshest concepts in Angular.
You’ll gradually build upon this foundation through insightful recipes, sample apps, and crystal-clear explanations. You’ll master authentication and authorization and achieve optimal performance through reactive programming and lazy loading, build complex yet flexible UIs with Router-first principles, and then integrate with backend systems using REST and GraphQL APIs.
You’ll cover modern tools like RxAngular, Qwik, and Signals. You’ll construct master/detail views using data tables and NgRx for state management. You’ll explore DevOps using Docker and build CI/CD pipelines necessary for high-performance teams.
By the end of this book, you’ll be proficient in leveraging Angular in enterprise and design robust systems that scale effortlessly.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 638

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Angular for Enterprise Applications

Third Edition

Build scalable Angular apps using the minimalist Router-first architecture

Doguhan Uluca

BIRMINGHAM—MUMBAI

“Angular” and the Angular Logo are trademarks of the Google LLC

Angular for Enterprise Applications

Third Edition

Copyright © 2024 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Senior Publishing Product Manager: Suman Sen

Acquisition Editor – Peer Reviews: Gaurav Gavas

Project Editor: Amisha Vathare

Content Development Editor: Shazeen Iqbal

Copy Editor: Safis Editing

Technical Editor: Anjitha Murali

Proofreader: Safis Editing

Indexer: Subalakshmi Govindhan

Presentation Designer: Ajay Patule

Developer Relations Marketing Executive: Priyadarshini Sharma

First published: May 2018

Second edition: May 2020

Third edition: January 2024

Production reference: 1240124

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-80512-712-3

www.packt.com

Contributors

About the author

Doguhan Uluca is a Principal Fellow at Excella in Washington DC, leading strategic GenAI initiatives and delivering critical systems. He is an industry-recognized expert in usability, mobility, performance, scalability, cybersecurity, and architecture. Doguhan is the author of the best-selling Angular for Enterprise Applications books, a speaker at 30+ conferences, and an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government. He enjoys building Lego, playing Go, and traveling.

Never say never. This edition is a testament to that. Many thanks to my family, Chanda and Ada, for their continued support and sacrifice, which allows me to spend many sleepless nights putting unreasonable amounts of time into untangling the complicated mess that web development is. Thanks also to my colleagues at Excella and the Angular community for their continued support.

About the reviewer

Jurgen Van de Moere is a Front-end architect based in Belgium. He worked as a Web developer and System engineer for large companies across Europe until 2012, when, driven by his passion for Web technologies, Jurgen decided to specialize in JavaScript and Angular. Since then, he has helped leading businesses to build secure, maintainable, testable, and scalable Angular applications. In his mission to share his knowledge with others, Jurgen serves as a private advisor and mentor to world-renowned global businesses and developers. Jurgen is actively involved in growing the Belgian Angular community as co-organizer of NG-BE, Belgium’s first-ever Angular conference. In 2016, he was awarded through the Google GDE program for being the first Google Developer Expert in Belgium for Web technologies.

Join our community on Discord

Join our community’s Discord space for discussions with the authors and other readers:

https://packt.link/AngularEnterpise3e

Contents

Preface

Who this book is for

What this book covers

To get the most out of this book

Get in touch

Angular’s Architecture and Concepts

Two Angulars

A brief history of web frameworks

The jQuery era

The server-side MVC era

Rich client era

Angular and the philosophies behind it

Deterministic releases

First-class upgrades

Maintainability

Angular Evergreen

TypeScript

Component architecture

Reactive programming

RxJS

Reactive data streams

Modular architecture

Standalone architecture

Angular Router

Lazy loading

State management

The Flux pattern

NgRx

NgRx component store

React.js architecture

Future of Angular

Summary

Further reading

Questions

Forms, Observables, Signals, and Subjects

Technical requirements

Great UX should drive implementation

Reactive versus template-driven forms

Adding Angular reactive forms

Adding and verifying components

Adding a search option to the weather service

Implementing a search

Limiting user inputs with throttle/debounce

Input validation and error messages

Template-driven forms with two-way binding

Component interaction with BehaviorSubject

Global events

Child-parent relationships with event emitters

Parent-child relationships with input binding

Sibling interactions with subjects

Managing subscriptions

Lifecycle of services

Exposé of a memory leak

Unsubscribing from a subscription

Subscribe with first or takeUntilDestroyed

Coding in the reactive paradigm

Binding to an observable with an async pipe

Tapping into an observable stream

Chaining API calls

Implementing a postal code service

Observable sequencing with switchMap

Using Angular Signals

Implementing dark mode

Replacing BehaviorSubject with signals

Generating apps with ChatGPT

Summary

Exercises

Questions

Architecting an Enterprise App

Succeeding as a technical lead or architect

Understand the business impact

Set parameters of success

Elastic leadership

Ingredients of a successful project

Agile software development

Agile engineering best practices

Engineering excellence and craftsmanship

Angular in an enterprise

Diverse coding paradigm support

Community support

Tools and techniques for high-performance apps

Runtime performance

Root cause of performance bottlenecks

Minimalist JavaScript solutions

ArrowJS

Qwik.js

Angular performance solutions

Server-side rendering and hydration

App shell

Service workers

RxAngular

Angular Signals

Build performance

Nx

esbuild

Test automation

Planning using Kanban and GitHub projects

Setting up a GitHub project

Customizing the Kanban board

Creating a prioritized backlog for your app

The 80-20 solution

Understanding line-of-business apps

Disciplined and balanced approach

Router-first architecture

Feature modules

Developing a roadmap and scope

Designing with lazy loading in mind

Implementing a walking skeleton

Achieve a stateless, data-driven design

Enforce a decoupled component architecture

Differentiate between user controls and components

Maximize code reuse with TypeScript and ES

Summary

Further reading

Questions

Creating a Router-First Line-of-Business App

Technical requirements

Creating LemonMart

Creating a router-first app

Configuring Angular and VS Code

Configuring Angular Material and styles

Designing LemonMart

Identifying user roles

Identifying high-level modules with a site map

Generating router-enabled modules

Designing the home route

Setting up default routes

RouterLink

Router outlet

Branding, customization, and Material icons

Branding

Color palette

Implementing a browser manifest and icons

Custom themes

Custom icons

Material icons

Feature modules with lazy loading

Configuring feature modules with components and routes

Lazy loading

Creating the walking skeleton

The manager module

User module

POS and inventory modules

PosModule

InventoryModule

Common testing module

Designing around major data entities

Defining entities

High-level UX design

Creating an artifacts wiki

Leveraging mock-ups in your app

Summary

Exercise

Further reading

Questions

Designing Authentication and Authorization

Technical requirements

Designing an auth workflow

JWT life cycle

TypeScript operators for safe data handling

Null and undefined checking

The conditional or ternary operator

The null coalescing operator

The nullish coalescing operator

Optional chaining

Implementing data entities and interfaces

Classes, Interfaces, and Enums

Reusable services leveraging OOP concepts

Creating an auth service

Implement an abstract auth service

Abstract functions

A cache service using localStorage

Caching the JWT

An in-memory auth service

Simple login

Logout

Resuming a JWT session

An HTTP interceptor

Summary

Further reading

Questions

Implementing Role-Based Navigation

Technical requirements

Dynamic UI components and navigation

Implementing the login component

Conditional navigation

Common validations for forms

UI service using environment provider

Side navigation

Role-based routing using guards

Route guards

Auth guards

Auth service fake and common testing providers

A Firebase authentication recipe

Create a Firebase application

Configuring Firebase authentication

Adding a Firebase auth provider to Angular

Providing a service using a factory

Summary

Further reading

Questions

Working with REST and GraphQL APIs

Technical requirements

Full-stack architecture

Minimal MEAN

NestJS

Working with monorepos

Nx monorepo

Git submodules

CircleCI config

Designing APIs

REST APIs

OpenAPI Spec

OpenAPI spec with Express

GraphQL APIs

GraphQL schema

Apollo with Express

Implementing APIs with Express.js

Bootstrapping the server

REST routes and versioning

GraphQL resolvers

Services

MongoDB ODM with DocumentTS

Implementing JWT auth

Authenticating middleware

Custom server auth provider

Summary

Exercise

Further reading

Questions

Recipes – Reusability, Forms, and Caching

Technical requirements

Implementing CRUD services with caching

Updating the cache

Multi-step responsive forms

Form controls and form groups

Stepper and responsive layout

Reusing repeating template behavior with directives

Attribute directives

Field error attribute directive

Calculated properties and DatePicker

Typeahead support

Dynamic form arrays

Creating shared components

Reviewing and saving form data

Scalable form architecture with reusable parts

Abstract form component

Implementing a reusable form part

Input masking

Custom controls with ControlValueAccessor

Implementing a custom rating control

Using custom controls in forms

Layouts using a grid list

Restoring cached data

Exercise

Summary

Further reading

Questions

Recipes – Master/Detail, Data Tables, and NgRx

Technical requirements

Loading data with resolve guard

Reusing components with binding and route data

Master/detail view using auxiliary routes

Data tables with pagination

NgRx store and effects

Implementing NgRx for LocalCast Weather

Comparing BehaviorSubject and NgRx

Setting up NgRx

Defining NgRx actions

Implementing NgRx effects

Impact of RxJS operators on actions

Implementing reducers

Registering with Store using selector

Dispatching store actions

Unit testing reducers and selectors

Unit testing components with MockStore

NgRx ecosystem

NgRx/Data

NgRx/ComponentStore

NgRx/Signals

Akita

Elf

Configuring server proxies with the Angular CLI

Implementing a global spinner with NgRx/SignalState

NgRx/SignalState

Pre-loading screens with HTML and CSS

Rewriting Angular apps with NgRx/SignalStore

RxJS and signal helpers

NgRx/SignalStore

Refactoring RxJS and NgRx code

NgRx Store to SignalStore

Services from Observables to Signals

Components from Observables to Signals

Summary

Exercises

Further reading

Questions

Releasing to Production with CI/CD

Technical requirements

Automated testing

Unit testing

Cypress e2e tests

Continuous integration

CircleCI

GitHub flow

Deploying to the cloud

Vercel

Deploying static files

Firebase

ng deploy

DevOps

Containerizing web apps using Docker

Anatomy of a Dockerfile

Installing Docker

Setting up npm scripts for Docker

Building and publishing an image to Docker Hub

npm scripts in VS Code

Docker extensions in VS Code

Working with containers in the cloud

Continuous deployment

Deploying to Vercel using CircleCI

Gated CI workflows

Code coverage reports

Code coverage in CI

Summary

Exercises

Further reading

Questions

Appendix A

Setting Up Your Development Environment

Recommended web development tools

CLI package managers

Installing Chocolatey for Windows

Installing Homebrew for macOS

Install automation for Windows and macOS

PowerShell script

Bash script

Project setup with the Angular CLI

Setting up your development directory

Generating your Angular application

Installing the Angular CLI

Initializing your Angular app

Optimizing VS Code for Angular

Configuring your project automatically

Summary

Further reading

Questions

Other Books You May Enjoy

Index

Landmarks

Cover

Index

Preface

Welcome to the wonderful world of Angular enterprise development! Standalone projects, signals, and the control flow syntax have injected fresh blood into the framework. At the time that this book is published, Angular 17.1 has been released with features to bring Signals-based components closer to reality, keeping the Angular ecosystem as vibrant as ever. If this trajectory holds, by Angular 20, the framework will be easier than ever to use and will make it possible to create reliable and high-performance applications of any size. This new edition of the book refocuses the content on enterprise architecture and continues the journey toward mastering sophisticated and scalable Angular solutions ready for complex business needs.

Much like the previous edition, this book has been meticulously designed to equip you with indispensable knowledge and pragmatic examples so you can architect, build, and deliver robust Angular applications. The emphasis remains on adopting an efficient and minimalist approach – maximizing the capabilities of Angular itself and eschewing unnecessary dependencies. This results in streamlined code that is simpler to maintain as Angular continues its rapid pace of progress.

The fundamental concepts you will learn from this book remain evergreen, even as tools and techniques continue to evolve. Router-first architecture, Angular components, the reactive programming model, the powerful routing system, and intuitive template syntax have stood the test of time. And they will provide you with a solid foundation as frameworks change and new versions emerge.

This edition includes extensively expanded coverage of key topics like change detection, state management, decoupled components, modular design, router orchestration, and integration with backend systems. You’ll also learn crucial real-world skills for enterprise development, like user authentication, data validation, optimization best practices, and CI/CD pipelines.

This definitive guide shares hard-won lessons on building web systems ready for the demands of any business. Over the years, the code and the content have been reviewed and improved by leading experts in the industry, and this edition is no different. Learn from the collective experience of these experts with actionable recipes, insider tips, and sample apps that showcase professional techniques.

Visit the companion site at https://AngularForEnterprise.com to join the community and stay current.

Who this book is for

This book is for experienced developers. If you’re new to Angular, start with the excellent tutorials at https://angular.dev/tutorials to become familiar with the basics and return to this book. As an Angular developer, you will deepen your understanding of the framework and be exposed to the entire gamut of designing and deploying an Angular application to production. You will learn about Angular patterns that are easy to understand and teach others. As a freelancer, you will pick up effective tools and technologies to deliver your Angular app securely, confidently, and reliably. As an enterprise developer, you will learn patterns and practices to write Angular applications with a scalable architecture and leverage popular enterprise tools.

What this book covers

Chapter 1, Angular’s Architecture and Concepts, introduces Angular as a mature platform for building sophisticated, high-performance web applications using TypeScript, RxJS, and NgRx. It introduces key concepts like reactive programming, the Flux pattern, standalone components, fine-grained reactivity with Signals, and the importance of keeping Angular updated.

Chapter 2, Forms, Observables, Signals, and Subjects, covers creating search functionality, using forms, enabling interaction between components, avoiding memory leaks, comparing imperative and reactive programming, chaining API calls, using signals for better performance, and building a small weather application to demonstrate basic Angular concepts.

Chapter 3, Architecting an Enterprise App, covers best practices and considerations for succeeding as a technical lead or architect on an enterprise Angular project, including ingredients for running a successful project, why Angular suits enterprise needs, performance optimization tools and techniques like the 80-20 rule and Router-first architecture, and agile planning with Kanban boards.

Chapter 4, Creating a Router-First Line-of-Business App, covers using the Angular CLI to generate project scaffolding and components, implementing branding and icons, debugging routers with DevTools, and the core tenets of router-first architecture – defining roles early, lazy loading, walking skeleton navigation, designing around data entities, completing high-level UX design, achieving stateless and decoupled components, differentiating controls and components, and maximizing code reuse with TypeScript/ECMAScript.

Chapter 5, Designing Authentication and Authorization, covers implementing token-based authentication with JWTs using TypeScript for safe data handling, building extendable services with OOP principles like inheritance and abstract classes, the fundamentals of caching and HTTP interceptors to preserve login state, and an in-memory authentication service for testing. The key topics are building secure authentication and authorization services and applying SOLID principles to make them extensible.

Chapter 6, Implementing Role-Based Navigation, covers designing conditional navigation experiences, creating reusable UI services for alerts, using route guards to control access, emphasizing server-side security, dynamically providing different auth providers based on environment, and implementing authentication with Firebase.

Chapter 7, Working with REST and GraphQL APIs, covers full-stack architecture using the MEAN stack – building a Node.js server with TypeScript, containerization with Docker, infrastructure as code with Docker Compose, CI/CD verification, designing REST APIs with OpenAPI and GraphQL with Apollo, implementing JWT authentication and RBAC middleware in Express, and building custom authentication providers in Angular using HttpClient and Apollo. The key topics are full-stack development, API design, RBAC, and end-to-end authentication.

Chapter 8, Recipes – Reusability, Forms, and Caching, covers building reusable forms, directives and user controls in Angular, including multi-step responsive forms, removing boilerplate code through inheritance and abstraction, dynamic form elements like date pickers, typeahead, and form arrays, interactive controls with input masking and custom components, seamless integration via ControlValueAccessor, and scaling form complexity linearly by extracting sections – as well as layout techniques like grid lists. The key topics are reusable, dynamic, and interactive form building blocks.

Chapter 9, Recipes – Master/Detail, Data Tables, and NgRx, completes coverage of major Angular application design considerations using router-first architecture and recipes to implement a line-of-business application, including editing users, resolving route data, reusing components, building master/detail views and data tables, implementing state management with NgRx or SignalStore, comparing state management options like NgRx Data, ComponentStore, Signals, Akita, and Elf, adding preload animations and global spinners, and previewing Angular’s signal-based future by refactoring an application to use SignalStore.

Chapter 10, Releasing to Production with CI/CD, covers implementing continuous integration/continuous delivery pipelines, emphasizing automated testing to enable rapid delivery in enterprises, configuring CI with CircleCI, enforcing quality gates with trunk-based development using GitHub flow, deploying to Vercel and Firebase, infrastructure as code techniques with Docker and NPM scripts, containerization and deployment to Google Cloud Run, gated CI workflows, CircleCI orchestration with workflows and orbs, code coverage metrics, and automated deployments to enable continuous delivery – allowing the rapid iteration and sharing of app builds.

Appendix A, Setting Up Your Development Environment, wraps things up with setting up efficient Angular development environments using CLI tools for automation and consistency across Windows and macOS, creating an initial Angular project, optimizing VS Code configuration, implementing automated linting and fixing for coding standard enforcement and error catching, documenting team norms through scripts, and how standardized environments and coding styles boost team productivity and troubleshooting.

To get the most out of this book

Set up your system for web development following the scripts covered in Appendix A, Setting Up Your Development Environment.If you’re new to Angular, complete the tutorials at https://angular.dev/tutorials.Follow the Technical requirements section at the beginning of each chapter and information boxes within sections.Check the latest code examples on GitHub at https://github.com/duluca.Sign up for the companion site to complete the self-assessment at https://angularforenterprise.com.For beginners, developers new to Angular, or inexperienced developers:Follow the book in the published order, coding your solution alongside the content in each chapter.It helps to be familiar with full-stack web development but is not a prerequisite.

Download the example code files

You can get the latest version of the example code files on GitHub. Four projects directly support the content in this book:

Web Development Environment Setup Scripts at https://github.com/duluca/web-dev-environment-setupLocal Weather App at https://github.com/duluca/local-weather-appLemonMart at https://github.com/duluca/lemon-martLemonMart Server at https://github.com/duluca/lemon-mart-server

In each chapter, you can find specific instructions to access chapter-specific versions of code examples referred to as stages. When demonstrating continuous integration and deployment configuration, Git branches and GitHub pull requests are utilized to demonstrate specific configuration elements.

Note that the code on GitHub may differ from the book’s content as Angular evolves.

Download the color images

We also provide a PDF file with color images of the screenshots/diagrams used in this book. You can download it here: https://packt.link/gbp/9781805127123.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and X handles. For example, “Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system.”

A block of code is set as follows:

{"name":"local-weather-app","version":"0.0.0","license":"MIT", ... }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

"scripts":{"ng":"ng","start":"ng serve","build":"ng build","test":"ng test","lint":"ng lint","e2e":"ng e2e"},

Any cross-platform or macOS-specific command-line input or output is written as follows:

$ brew tap caskroom/cask

Windows-specific command-line input or output is written as follows:

PS> Set-ExecutionPolicy AllSigned; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Bold: Indicates a new term, an important word, or words that you see on the screen. For instance words in menus or dialog boxes also appear in the text like this. For example: “Select System info from the Administration panel.”

Warnings or important notes appear like this.

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book’s title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you reported this to us. Please visit http://www.packtpub.com/submit-errata, click Submit Errata, and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit http://authors.packtpub.com.

Share your thoughts

Once you’ve read Angular for Enterprise Applications, Third Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781805127123

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

1

Angular’s Architecture and Concepts

Angular is a popular Single-Page Application (SPA) framework for building web applications. It is often preferred in enterprise application development because it is an opinionated, batteries-included framework that supports type-checking with TypeScript and concepts like Dependency Injection (DI) that allow for engineering scalable solutions by large teams. In contrast, React is a flexible and unopinionated library rather than a complete framework, requiring developers to pick their flavor from the community to build fully featured applications.

React is undoubtedly the more popular choice of the two. The numbers don’t lie. React’s easier learning curve and deceptively small and simple starting point have attracted the attention of many developers. The many “Angular vs React” articles you have undoubtedly encountered online add to the confusion. These articles are usually too shallow, often contain misleading information about Angular, and lack insights into the very bright future of Angular.

This chapter aims to give you a deeper understanding of why Angular exists, the variety of patterns and paradigms you can leverage to solve complex problems, and, later in the book, the pitfalls to avoid as you scale your solution. It’s important to take your time to read through this material because every journey begins with a choice. The real story of your choice today can only be written several years into a project when it’s too late and expensive to switch technologies.

This chapter covers the following topics:

Two AngularsA brief history of web frameworksAngular and the philosophies behind itComponent architectureReactive programmingModular architectureStandalone architectureAngular RouterState managementReact.js architectureThe future of Angular

Chapter 2, Forms, Observables, Signals, and Subjects, covers Angular fundamental concepts and building blocks. Chapter 3, Architecting an Enterprise App, covers technical, architectural, and tooling concerns for delivering large applications. With Chapter 4, Creating a Router-First Line-of-Business App, we dive into creating scalable Angular applications ready for the enterprise.

Each chapter introduces new concepts and progressively builds on best practices while covering optimal working methods with popular open-source tools. Along the way, tips and information boxes provide additional background and history, numbered steps, and bullet points that describe actions you need to take.

The code samples provided in this book have been developed using Angular 17. Since the second edition, significant changes occurred in the JavaScript and Angular ecosystems. The transition to Angular’s Ivy engine meant some third-party tools stopped working. ESLint has superseded TSLint. Karma and Jasmine have become outdated and superseded by Jest or the more modern Vitest. Significant headway was made in replacing commonjs modules with ES modules (ESM).The totality of these changes meant that much of the second edition’s supporting tools were beyond repair. As a lesson learned, the example projects now utilize minimal tooling to allow for the best possible DevEx with the least possible amount of npm packages installed. The core samples of the book, which intentionally avoided third-party libraries, were initially written for Angular 5 and have survived the test of time. This book adopts the Angular Evergreen motto and encourages incremental, proactive, and timely upgrades of your dependencies to maintain the health of your project and your team.

This book is supported by the companion site https://AngularForEnterprise.com. Visit the site for the latest news and updates.

The world of JavaScript, TypeScript, and Angular is constantly changing. To maintain consistency for my readers, I published a collection of open-source projects that support the content of the book:

Figure 1.1: Code developed in support of this book

The diagram above shows you the moving parts that make up the technical content supporting this book. Each component is detailed in the coming chapters. The code samples contain chapter-by-chapter snapshots and the final state of the code. The most up-to-date versions of the sample code for the book are on GitHub at the repositories linked below:

For Chapters 2 and 9, LocalCast Weather: https://github.com/duluca/local-weather-appFor Chapters 4 to 10, Lemon Mart: https://github.com/duluca/lemon-martFor Chapter 5, Lemon Mart Server: https://github.com/duluca/lemon-mart-server

You may read more about updating Angular in the supplemental reading, Keeping Angular and Tools Evergreen, available at https://angularforenterprise.com/evergreen.

Now that you’re oriented with the book’s structure and supporting content, and before we dive into a prolonged history of the web, let’s first disambiguate the two major architectures of Angular and the underlying themes that motivated a dramatic rewrite of the framework in 2016.

Two Angulars

In its original incarnation, Angular.js, aka 1.x, pioneered the SPA era, a technique that tricks the browser into thinking that a single index.html houses an interactive application containing many pages. Angular.js also popularized the concept of two-way binding in web development, which automatically updates the view to match the state of the ViewModel. To implement such a feature, Angular.js used Change Detection to keep track of Document Object Model (DOM) elements of the browser and the ViewModel state of the application.

Change Detection depends on a sophisticated rendering loop to detect user interactions and other events to determine if the application needs to react to changes. Whenever a rendering loop is involved, like in games, performance can be measured as a frame rate expressed in Frames per Second (FPS). A slow change detection process results in a low FPS count, translating into a choppy User Experience (UX). With the demand for more interactive and complicated web applications, it became clear that the internal architecture of Angular.js couldn’t be improved to maintain a consistent FPS output. However, UX and performance are only one side of the experience story. As an application grows more complicated better tooling is needed to support a great Developer Experience (DevEx) – sometimes called DevX or DX – which is key to developer wellbeing.

The Angular 2 rewrite, now simply referred to as Angular, aimed to solve both sides of the problem. Before frameworks and libraries like React, Angular, and Vue, we suffered from unmanaged complexity and JavaScript-framework-of-the-week syndrome. These frameworks succeeded with promises to fix all problems, bring about universally reusable web components, and make it easier to learn, develop, and scale web applications- at least for a while, some being better than others during different periods. The same problems that plagued early SPA are returning as the demand for ever more complicated web experiences increases, and the tooling to resolve these problems grows ever complex. To master Angular or any other modern framework, it is critical to learn about the past, present, and future of web development. The adolescent history of the web has taught us a couple of essential lessons. First, change is inevitable, and second, the developer’s happiness is a precious commodity that can make or break entire companies.

As you can see, Angular’s development has been deeply impacted by performance, UX, and DevEx concerns. But this wasn’t a unique problem that only impacted Angular. Let’s roll back the clock further and look at the last quarter century or so of web development history so that you can contextualize modern frameworks like Angular, React, and Vue.

A brief history of web frameworks

It is essential to understand why we use frameworks such as Angular, React, or Vue in the first place to get an appreciation of the value they bring. As the web evolves, you may find that, in some cases, the framework is no longer necessary and should be discarded, and in others, critical to your business and must be retained. Web frameworks rose as JavaScript became more popular and capable in the browser. In 2004, the Asynchronous JavaScript and XML (AJAX) technique became very popular in creating websites that did not have to rely on full-page refreshes to create dynamic experiences, utilizing standardized web technologies like HTML, JavaScript/ECMAScript, and CSS. Browser vendors are supposed to implement these technologies as defined by the World Wide Web Consortium (W3C).

Internet Explorer (IE) was the browser that most internet users relied on at the time. Microsoft used its market dominance to push proprietary technologies and APIs to secure IE’s edge as the go-to browser. Things started to get interesting when Mozilla’s Firefox challenged IE’s dominance, followed by Google’s Chrome browser. As both browsers successfully gained significant market share, the web development landscape became a mess. New browser versions appeared at breakneck speed. Competing corporate and technical interests led to the diverging implementation of web standards.

This fracturing created an unsustainable environment for developers to deliver consistent experiences on the web. Differing qualities, versions, and names of implementations of various standards created an enormous challenge: successfully writing code that could manipulate the DOM of a browser consistently. Even the slightest difference in the APIs and capabilities of a browser would be enough to break a website.

The jQuery era

In 2006, jQuery was developed to smooth out the differences between APIs and browser capabilities. So instead of repeatedly writing code to check browser versions, you could use jQuery, and you were good to go. It hid away all the complexities of vendor-specific implementations and gracefully filled the gaps when there were missing features. For almost a decade, jQuery became the web development framework. It was unimaginable to write an interactive website without using jQuery.

However, to create vibrant user experiences, jQuery alone was not enough. Native web applications ran all their code in the browser, which required fast computers to run the dynamically interpreted JavaScript and render web pages using complicated object graphs. In the 2000s, many users ran outdated browsers on relatively slow computers, so the user experience wasn’t great.

Combined with AJAX, jQuery enabled any web developer to create interactive and dynamic websites that could run on any browser without running expensive server hardware and software. To have a solid understanding of the architectural nuances of code that runs on the client and server side, consider a traditional three-tier software architecture. Each tier is described in three primary layers, as shown in the following diagram:

Figure 1.2: Three-tiered software architecture

The presentation layer contains User Interface (UI) related code. This is primarily code that runs on the client, referred to as a thick client. However, the presentation logic can instead reside on the server. In these cases, the client becomes a thin client. The business layer contains business logic and normally resides on the server side. An undisciplined implementation can result in business logic spreading across all three layers. This means a bug or a change in the logic needs to be implemented in many locations. In reality, no individual can locate every occurrence of this logic and can only partially repair code. This, of course, results in the creation of more exotic bugs. The persistence layer contains code related to data storage.

To write easy-to-maintain and bug-free code, our overall design goal is to aim for low coupling and high cohesion between the components of our architecture. Low coupling means that pieces of code across these layers shouldn’t depend on each other and should be independently replaceable. High cohesion means that pieces of code related to each other, like code regarding a particular domain of business logic, should remain together. For example, when building an app to manage a restaurant, the code for the reservation system should be together and not spread across other systems like inventory tracking or user management.

With jQuery and AJAX, writing thick clients for the web became possible, making it easier than ever to write unmaintainable code. Modern web apps have way more moving parts than a basic three-tiered application. The diagram that follows shows additional layers that fit around the presentation, business, and persistence layers:

Figure 1.3: Modern Web Architecture

You can observe the essential components of modern web development in the expanded architecture diagram, which includes an API layer that usually transforms and transfers data between the presentation and business layers. Beyond code within the operating environment, the tools and best practices layer defines and enforces patterns used to develop the software. Finally, the testing layer defines a barrage of automated tests to ensure the correctness of code, which is crucial in today’s iterative and fast-moving development cycles.

While there was a big appetite to democratize web development with thick clients primarily consuming client-side computing resources, the tooling wasn’t ready to enforce proper architectural practices and deliver maintainable software. This meant businesses kept investing in server-side rendering technologies.

The server-side MVC era

In the late 2000s, many businesses still relied on server-side rendered web pages. The server dynamically created all the HTML, CSS, and data needed to render a page. The browser acted as a glorified viewer that would display the result. The following is a diagram that shows an example architectural overview of a server-side rendered web application in the ASP.NET MVC stack:

Figure 1.4: Server-side rendered MVC architecture

Model-View-Controller (MVC) is a typical pattern of code that has data manipulation logic in models, business logic in controllers, and presentation logic in views. In the case of ASP.NET MVC, the controller and model are coded using C#, and views are created using a templated version of HTML, JavaScript, and C#. The result is that the browser receives HTML, JavaScript, and needed data, and through jQuery and AJAX magic, web pages look to be interactive. Server-side rendering and MVC patterns are still popular and in use today. There are justified niche uses, such as Facebook.com. Facebook serves billions of devices that range from the very slow to the very fast. Without server-side rendering, it would be impossible for Facebook to guarantee consistent UX across its user base.

The combination of server-side rendering and MVC is an intricate pattern to execute; there are a lot of opportunities for presentation and business logic to become co-mingled. To ensure the low coupling of components, every member of the engineering team must be very experienced. Teams with a high concentration of senior developers are hard to come by, which would be an understatement.

Further complicating matters is that C# (or any other server-side language) cannot run natively in the browser. So developers who work on server-side rendered applications must be equally skilled at using frontend and backend technologies. It is easy for inexperienced developers to unintentionally co-mingle presentation and business logic in such implementations. When this happens, the inevitable UI modernization of an otherwise well-functioning system becomes impossible. In other words, to replace the sink in your kitchen with a new one, you must renovate your entire kitchen. Due to insufficient architecture, organizations spend millions of dollars writing and rewriting the same applications every decade.

Rich client era

In the 2000s, it was possible to build rich web applications decoupled from their server APIs using Java Applets, Flash, or Silverlight. However, these technologies relied on browser plugins that needed a separate installation. Most often, these plugins were outdated, created critical security vulnerabilities, and consumed too much power on mobile computers. Following the iPhone revolution in 2008, it was clear such plugins wouldn’t run on mobile phones, despite the best attempts by the Android OS. Besides, Apple CEO Steve Jobs’ disdain for such inelegant solutions marked the beginning of the end for the support of such technologies in the browser.

In the early 2010s, frameworks like Backbone and AngularJS started showing up, demonstrating how to build rich web applications with a native feel and speed and do so in a seemingly cost-effective way. The following diagram shows a Model-View-ViewModel (MVVM) client with a Representational State Transfer (REST) API. When we decouple the client from the server via an API, we can architecturally enforce the implementation of presentation and business logic separately. Theoretically, this RESTful web services pattern would allow us to replace the kitchen sink as often as possible without remodeling the entire kitchen.

Figure 1.5: Rich-client decoupled MVVM architecture

The MVVM architecture above shows a near doubling of boxes compared to the server-side MVC architecture. Does this mean we need to write twice as much code? Yes and no. Yes, we need to write more code to maintain a disciplined architecture; however, over time, we’ll write a lot less code because of the overall maintainability of the solution. The architecture surrounding the presentation logic indeed becomes a lot more complicated. The client and server must implement their presentation/API, business, and persistence layers.

Unfortunately, many early development efforts leveraging frameworks like Backbone and AngularJS collapsed under their weight because they failed to implement the client-side architecture properly.

These early development efforts also suffered from ill-designed RESTful Web APIs. Most APIs didn’t version their URIs, making it very difficult to introduce new functionality while supporting existing clients. Further, APIs often returned complicated data models exposing their internal relational data models to web apps. This design flaw creates a tight coupling between seemingly unrelated components/views written in HTML and models created in SQL. If you don’t implement additional layers of code to translate or map the structure of data, then you create an unintentional and uncontrolled coupling between layers. Over time, dealing with such coupling becomes very expensive very quickly, in most cases necessitating significant rewrites.

Today, we use the API layer to flatten the data model before sending it to the client to avoid such problems. Newer technologies like GraphQL go further by exposing a well-defined data model and letting the consumer query for the exact data it needs. Using GraphQL, the number of HTTP requests and the amount of data transferred over the wire is optimal without the developers having to create many specialized APIs.

Backbone and AngularJS proved that creating web applications that run natively in the browser was viable. All SPA frameworks at the time relied on jQuery for DOM manipulation. Meanwhile, web standards continued to evolve, and evergreen browsers supporting new standards became commonplace. However, change is constant, and the evolution of web technologies made it unsustainable to gracefully evolve this first generation of SPA frameworks, as I hinted in the Two Angulars section.

The next generation of web frameworks needed to solve many problems; they needed to enforce good architecture, be designed to evolve with web standards and be stable and scalable to enterprise needs without collapsing. Also, these new frameworks needed to gain acceptance from developers, who were burned out with too many rapid changes in the ecosystem. Remember, unhappy developers do not create successful businesses. Achieving these goals required a clean break from the past, so Angular and React emerged as platforms to address the problems of the past in different ways. As you’ll discover in the following sections, Angular offers the best tools and architecture for building scalable enterprise-grade applications.

Angular and the philosophies behind it

Angular is an open-source project maintained by Google and a community of developers. The new Angular platform vastly differs from the legacy framework you may have used. In collaboration with Microsoft, Google made TypeScript the default language for Angular. TypeScript is a superset of JavaScript that enables developers to target legacy browsers, such as Internet Explorer 11, while allowing them to write modern JavaScript code that works in evergreen browsers such as Chrome, Firefox, and Edge. The legacy version of Angular in the 1.x range, called AngularJS, was a monolithic JavaScript SPA framework. The modern version, Angular 2+, is a platform capable of targeting browsers, hybrid-mobile frameworks, desktop applications, and server-side rendered views.

In the prior generation, upgrading to new versions of AngularJS was risky and costly because even minor updates introduced new coding patterns and experimental features. Each update introduced deprecations or refactored API surfaces, requiring rewriting of large portions of code. Also, updates were delivered in uncertain intervals, making it impossible for a team to plan resources to upgrade to a new version. The release methodology eventually led to an unpredictable, ever-evolving framework with seemingly no guiding hand to carry code bases forward. If you used AngularJS, you were likely stuck on a particular version because the specific architecture of your code base made it very difficult to move to a new version. In 2018, the Angular team released the last major update to AngularJS with version 1.7. This release marked the beginning of the end for the legacy framework, with end-of-life coming in January 2022.

Deterministic releases

Angular improves upon AngularJS in every way imaginable. The platform follows semver, as defined at https://semver.org/, where minor version increments denote new feature additions and potential deprecation notices for the following major version, but no breaking changes. Furthermore, the Angular team at Google has committed to a deterministic release schedule with major versions released every 6 months. After this 6-month development window, starting with Angular 4, all major releases receive LTS with bug fixes and security patches for an additional 12 months. From release to end-of-life, each major version receives updates for 18 months. Refer to the following chart for the tentative release and support schedule for Angular:

Figure 1.6: Actively supported versions

What does this mean for you? You can be confident that your Angular code is supported and backward compatible for approximately 24 months, even if you make no changes to it. For example, if you wrote an Angular app in version 17 in November 2023, and you didn’t use any deprecated functionality, your code will be runtime compatible with Angular 18 and supported through May 2025. To upgrade your Angular 17 code to Angular 19, you must ensure that you’re not using any deprecated APIs that receive a deprecation notice in Angular 18.

In practice, most deprecations are minor and are straightforward to refactor. Unless you work with low-level APIs for highly specialized user experiences, the time and effort it takes to update your code base should be minimal. However, this is a promise made by Google and not a contract. The Angular team has a significant incentive to ensure backward compatibility because Google runs around 1,000+ Angular apps with a single version of Angular active at any one time throughout the organization. So, by the time you read this, all of Google’s 1,000+ apps will be running on the latest version of Angular.

First-class upgrades

You may think Google has infinite resources to update thousands of apps regularly. Like any organization, Google, too, has limited resources. It would be too expensive to assign a dedicated team to maintain every app. So the Angular team must ensure compatibility through automated tests and make it as painless as possible to move through major releases in the future. In Angular 6 ng update was introduced, making the update process a first-class experience.

The Angular team continually improves its release process with automated CLI tools to make upgrading deprecated functionality a mostly automated, reasonable endeavor. Air France and KLM demonstrated this strategy’s benefits, reducing their upgrade times from 30 days in Angular 2 to 1 day in Angular 7.

A predictable and well-supported upgrade process is excellent news for developers and organizations. Instead of being perpetually stuck on a legacy version of Angular, you can plan and allocate the necessary resources to keep moving your application to the future without costly rewrites. As I wrote in a 2017 blog post, The Best New Feature of Angular 4, at https://bit.ly/NgBestFeature, the message is clear:

For developers and managers: Angular is here to stay, so you should be investing your time, attention, and money in learning it – even if you’re currently in love with some other framework.

For decision makers (CIOs, CTOs, and so on): Plan to begin your transition to Angular in the next 6 months. It’ll be an investment you’ll be able to explain to business-minded people, and your investment will pay dividends for many years to come, long after the initial LTS window expires, with graceful upgrade paths to Angular vNext and beyond.

So why do Google (Angular) and Microsoft (TypeScript and Visual Studio Code) give away such technologies for free? There are multiple reasons:

A sophisticated framework that makes it easy to develop web apps demonstrates technical prowess, which retains and attracts developer talent.An open-source framework enables the proving and debugging of new ideas and tools with millions of developers at scale.Allowing developers to create great web experiences drives more business for Google and Microsoft.

I don’t see any nefarious intent here and welcome open, mature, and high-quality tools that, if necessary, I can tinker with and bend to my own will. Not having to pay for a support contract for a proprietary piece of tech is a welcome bonus.

Beware - looking for Angular help on the web may be tricky. You’ll need to disambiguate between AngularJS or Angular, which may be referred to as Angular2, but also be aware that some advice given about versions 13 or below may not apply to 14+ because of the rendering engine change to Ivy. I always recommend reading the official documentation when learning. Documentation for Angular is at https://angular.dev. This should not be confused with angularjs.org, which is about the legacy AngularJS framework or the retired angular.io site.

For the latest updates on the upcoming Angular releases, view the official release schedule at https://angular.dev/reference/releases.

Maintainability

Your time is valuable, and your happiness is paramount, so you must carefully choose the technologies to invest your time in. With this in mind, we must answer why Angular is the tool you should learn over React, Vue, or others. Angular is a great framework to start learning. The framework and the tooling help you get off the ground quickly and continue being successful, with a vibrant community and high-quality UI libraries you can use to deliver exceptional web applications. React and Vue are great libraries with their strengths and weaknesses. Every tool has its place and purpose.

In some cases, React is the right choice for a project, while Vue is the right one in others. Becoming somewhat proficient in other web frameworks can only help further your understanding of Angular and make you a better developer overall. SPAs such as Backbone and AngularJS grabbed my full attention in 2012 when I realized the importance of decoupling frontend and backend concerns. Server-side rendered templates are nearly impossible to maintain and are the root cause of many expensive rewrites of software systems. If you care about creating maintainable software, you must abide by the prime directive: keep the business logic behind the API decoupled from the presentation logic implemented in the UI.

Angular neatly fits the Pareto principle or the 80-20 rule. It has become a mature and evolving platform, allowing you to achieve 80% of tasks with 20% of the effort. As mentioned in the previous section, every major release is supported for 18 months, creating a continuum of learning, staying up to date, and deprecating old features. From the perspective of a full-stack developer, this continuum is invaluable since your skills and training will remain relevant and fresh for many years to come.

The philosophy behind Angular is to err on the side of configuration over convention. Although convention-based frameworks may seem elegant from the outside, they make it difficult for newcomers to pick up the framework. Configuration-based frameworks aim to expose their inner workings through explicit configuration and hooks, where you can attach your custom behavior to the framework. In essence, where AngularJS had tons of magic, which can be confusing, unpredictable, and challenging to debug, Angular tries to be non-magical.

Configuration over convention results in verbose coding. Verbosity is a good thing. Terse code is the enemy of maintainability, only benefiting the original author. As Andy Hunt and David Thomas put it in The Pragmatic Programmer:

Remember that you (and others after you) will be reading the code many hundreds of times, but only writing it a few times.

Further, Andy Hunt’s Law of Design dictates:

If you can’t rip every piece out easily, then the design sucks.

Verbose, decoupled, cohesive, and encapsulated code is the key to future-proofing your code. Through its various mechanisms, Angular enables the proper execution of these concepts. It eliminates many custom conventions invented in AngularJS, such as ng-click, and introduces a more natural language that builds on the existing HTML elements and properties. As a result, ng-click becomes (click), extending HTML rather than replacing it.

Next, we’ll review Angular’s evergreen mindset and the reactive programming paradigm, the latest extensions of Angular’s initial philosophy.

Angular Evergreen

When you’re learning Angular, you’re not learning one specific version of Angular but a platform that is continually evolving. Since the first drafts, I designed this book to deemphasize the specific version of Angular you’re using. The Angular team champions this idea. Over the years, I have had many conversations with the Angular team and thought leaders within the community and listened to many presentations. As a result, you can depend on Angular as a mature web development platform. Angular frequently receives updates with great attention to backward compatibility. Furthermore, any code made incompatible by a new version is brought forward with help from automated tools or explicit guidance on updating your code by locating the Angular Update Guide on https://angular.dev/update, so you’re never left guessing or scouring the internet for answers. The Angular team is committed to ensuring you – the developer – have the best web development experience possible.

To bring this idea front and center with developers, several colleagues and I have developed and published a Visual Studio Code extension called Angular Evergreen, as shown in the following image:

Figure 1.7: Angular Evergreen VS Code extension

This extension detects your current version of Angular and compares it to the latest and next releases of Angular. Releases labeled next are meant for early adopters and testing your code’s compatibility with an upcoming version of Angular. Do not use next-labeled releases for production deployments.

Find more information, feature requests, and bug reports on the Angular Evergreen extension at https://AngularEvergreen.com.

One of the critical components of Angular that allows the platform to remain evergreen is TypeScript. TypeScript allows new features to be implemented efficiently while supporting older browsers, so your code can reach the widest audience possible.

TypeScript

Angular is coded using TypeScript. Anders Hejlsberg of Microsoft created TypeScript to address several major issues with applying JavaScript at a large enterprise scale.

Anders Hejlsberg is the creator of Turbo Pascal and C# and Delphi’s chief architect. Anders designed C# to be a developer-friendly language built upon the familiar syntax of C and C++. As a result, C# became the language behind Microsoft’s popular .NET Framework. TypeScript shares a similar pedigree with Turbo Pascal and C# and their ideals, which made them a great success.

JavaScript is a dynamically interpreted language where the browser parses and understands the code you write at runtime. Statically typed languages like Java or C# have an additional compilation step where the compiler can catch programming and logic errors during compile time. Detecting and fixing bugs at compile time versus runtime is much cheaper. TypeScript brings the benefits of statically typed languages to JavaScript by introducing types and generics. However, TypeScript is not a compiler in the traditional sense. It is a transpiler. A compiler builds code into machine language with C/C++ or Intermediary Language (IL) with Java or C#. A transpiler, however, transforms the code from one dialect to another. So, when TypeScript code is built, compiled, or transpiled, the result is pure JavaScript.

JavaScript’s official name is ECMAScript. The language’s feature set and syntax are maintained by the ECMA Technical Committee 39, or TC39 for short.

Transpilation has another significant benefit. The same tooling that converts TypeScript to JavaScript can be used to rewrite JavaScript with a new syntax to an older version that older browsers can parse and execute. Between 1999 and 2009, the JavaScript language didn’t see any new features. ECMAScript abandoned version 4 due to various technical and political reasons. Browser vendors have struggled to implement new JavaScript features within their browsers, starting with the introduction of ES5 and then ES2015 (also known as ES6).

As a result, user adoption of these new features has remained low. However, these new features meant developers could write code more productively. This created a gap known as the JavaScript Feature Gap, as demonstrated by the graphic that follows:

Figure 1.8: The JavaScript Feature Gap

The JavaScript Feature Gap is sliding, as TC39 has committed to updating JavaScript every year. As a result, TypeScript represents JavaScript’s past, present, and future. You can use future features of JavaScript today and still be able to target browsers of the past to maximize the audience you can reach. In 2023, this gap is smaller than ever, with ES2022 being a mature language with wide support from every major browser.

Now, let’s go over Angular’s underlying architecture.

Component architecture

Angular follows the MV* pattern, a hybrid of the MVC and MVVM patterns. Previously, we went over the MVC pattern. At a high level, the architecture of both patterns is relatively similar, as shown in the diagram that follows:

Figure 1.9: MV* architecture

The new concept here is the ViewModel, which represents the glue code that connects your view to your model or service. In Angular, this glue is known as binding. Whereas MVC frameworks like Backbone or React must call a render method to process their HTML templates, in Angular, this process is seamless and transparent for the developer. Binding is what differentiates an MVC application from an MVVM one.

The most basic unit of an Angular app is a component. A component combines a JavaScript class, written in TypeScript, and an Angular template, written in HTML, CSS, and TypeScript, as one element. The class and the template fit together like a jigsaw puzzle through bindings so that they can communicate with each other, as shown in the diagram that follows:

Figure 1.10: Anatomy of a component

Classes are an Object-Oriented Programming (OOP) construct. If you invest the time to dig deeper into the OOP paradigm, you will vastly improve your understanding of how Angular works. The OOP paradigm allows for the Dependency Injection (DI) of dependent services in your components, so you can make HTTP calls or trigger a toast message to be displayed to the user without pulling that logic into your component or duplicating your code. DI makes it very easy for developers to use many interdependent services without worrying about the order of the instantiation, initialization, or destruction of such objects from memory.

Angular templates allow similar code reuse via directives, pipes, user controls, and other components. These are pieces of code that encapsulate highly interactive end-user code. This kind of interactivity code is often complicated and convoluted and must be kept isolated from business logic or presentation logic to keep your code maintainable.

Angular 17 introduces a new control flow syntax (in preview), which replaces directives like *ngIf with @if, *ngFor with @for, and *ngSwitch with @switch and introduces @empty, @defer, contextual variables, and conditional statements. The new syntax makes templates easier to read and avoids importing legacy directives to every component in a standalone project. This book will exclusively use the control flow syntax.

You can run npx ng generate @angular/core:control-flow to convert your existing template to the new syntax.

Angular apps can be created in two different ways:

An NgModule project A standalone project

As of Angular 17, the default way is to bootstrap your app as a standalone project. This approach has many benefits, as further explained in The Angular Router section below. There is a lot of new terminology to learn, but modules as a concept aren’t going away. It’s just that they’re no longer required.

Whether your app starts with bootstrapApplication or bootstrapModule, at the root level of your application, Angular components, services, directives, pipes, and user controls are provided to the bootstrapApplication function or organized under modules. The root level configuration renders your first component, injects any services, and prepares any dependencies it may require. In a standalone app, you can lazily load individual components.

You may also introduce feature modules to lazy load groups of services and components. All these features help the initial app load up very quickly, improving First Contentful Paint times because the framework doesn’t have to download and load all web application components in the browser simultaneously. For instance, sending code for the admin dashboard to a user without admin privileges is useless.