Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Angular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture
Angular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture
Angular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture
Ebook1,582 pages6 hours

Angular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateJan 31, 2024
ISBN9781805125037
Angular for Enterprise Applications: Build scalable Angular apps using the minimalist Router-first architecture
Author

Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.

Related to Angular for Enterprise Applications

Related ebooks

Internet & Web For You

View More

Reviews for Angular for Enterprise Applications

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Angular for Enterprise Applications - Doguhan Uluca

    cover.png

    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-setup

    Local Weather App at https://github.com/duluca/local-weather-app

    LemonMart at https://github.com/duluca/lemon-mart

    LemonMart 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

    Qr code Description automatically generated

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

    Submit your proof of purchase

    That’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 Angulars

    A brief history of web frameworks

    Angular and the philosophies behind it

    Component architecture

    Reactive programming

    Modular architecture

    Standalone architecture

    Angular Router

    State management

    React.js architecture

    The 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:

    A screenshot of a computer Description automatically generated

    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-app

    For Chapters 4 to 10, Lemon Mart: https://github.com/duluca/lemon-mart

    For 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

    Enjoying the preview?
    Page 1 of 1