57,59 €
This second edition of Angular for Enterprise-Ready Web Applications is updated with in-depth coverage of the evergreen Angular platform. You’ll start by mastering Angular programming fundamentals. Using the Kanban method and GitHub tools, you’ll build great-looking apps with Angular Material and also leverage reactive programming patterns with RxJS, discover the flux pattern with NgRx, become familiar with automated testing, utilize continuous integration using CircleCI, and deploy your app to the cloud using Vercel Now and GCloud. You will then learn how to design and develop line-of-business apps using router-first architecture with observable data anchors, demonstrated through oft-used recipes like master/detail views, and data tables with pagination and forms. Next, you’ll discover robust authentication and authorization design demonstrated via integration with Firebase, API documentation using Swagger, and API implementation using the MEAN stack. Finally, you will learn about DevOps using Docker, build a highly available cloud infrastructure on AWS, capture user behavior with Google Analytics, and perform load testing. By the end of the book, you’ll be familiar with the entire gamut of modern web development and full-stack architecture, learning patterns and practices to be successful as an individual developer on the web or as a team in the enterprise.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 859
Veröffentlichungsjahr: 2020
Angular for Enterprise-Ready Web Applications
Second Edition
Build and deliver production-grade and cloud-scale evergreen web apps with Angular 9 and beyond
Doguhan Uluca
BIRMINGHAM - MUMBAI
Angular for Enterprise-Ready Web Applications
Second Edition
Copyright © 2020 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.
Producer: Jonathan Malysiak
Acquisition Editor – Peer Reviews: Suresh Jain
Content Development Editor: Alex Patterson
Technical Editor: Aniket Shetty
Project Editor: Carol Lewis
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Presentation Designer: Pranit Padwal
First published: May 2018
Second edition: May 2020
Production reference: 1280520
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-83864-880-0
www.packt.com
packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.Packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.Packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Doguhan Uluca is a technical fellow for Excella in Washington, DC, and a Google Developers Expert in Angular and web technologies. He is a software development, agile, and cloud engineering expert. Doguhan is passionate about teaching technology and open source software. He is a speaker, an author whose work includes the best-selling Angular 6 for Enterprise-Ready Web Applications, and an active contributor in the OSS community. Doguhan enjoys recording music, playing Go, building Lego, and mixology. Find him on Twitter as @duluca.
Dear Chanda and Ada, thank you for your great sacrifice and amazing support in making this second edition happen. Mr. Caulkins, "What doesn't kill you makes you stronger," so now we're stronger. Also, thanks to Kenton Bocock, Brendan Sawyer, Andrej Rasevic, Alex Hoffman, Jan-Niklas Wortmann, Gleb Bahmutov, Mamadou Toure, and my mentor Fadi Stephan for all the ideas, OSS contributions, and collaboration.
Brendon Caulkins is a full-stack developer based in the Washington DC area. He has over a decade of product testing experience evaluating hardware and software systems, including writing custom test applications. He is focused on delivering high-quality and well-tested line-of-business applications that leverage JavaScript, Java, Ruby, and Docker. He enjoys mentoring and developing innovative and efficient solutions as a Technical Lead on internal, commercial, and federal projects. He speaks at local conferences and meetups about agile software processes, Angular, and automated testing best practices. Brendon enjoys hiking, science fiction, board games, video games, and still plays with LEGO and toy soldiers. He can be found on the interwebs via Twitter, as @BrendonCaulkins.
Aayush Arora is a Google Developer Expert and the founder of FilterPixel, an AI-based photography start-up. An innovation strategist and Massachusetts Institute of Technology Bootcamp graduate, he brings more than 5 years of experience in web development and accessibility with his expertise in Angular framework.
He has made open source contributions in repositories including NASA, CloudCV, and FOSSASIA, and has been continuously contributing to the growth of these communities.
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Introduction to Angular and Its Concepts
A brief history of web frameworks
Introduction to Angular
Angular's philosophy
Angular Evergreen
TypeScript
Basic Angular architecture
The reactive development paradigm
RxJS
Reactive data streams
Advanced Angular architecture
The Angular Router
Lazy loading
State management
The Flux pattern
NgRx
React.js architecture
Notable Angular features
Angular 6
Angular 8
Angular 9
Summary
Further reading
Questions
Setting Up Your Development Environment
CLI package managers
Installing Chocolatey for Windows
Installing Homebrew for macOS
Installing development tools
Git and GitHub Desktop
Why use GitHub?
Why use GitHub Desktop?
Installing Git and GitHub Desktop
Using your GitHub credentials in Git
Node.js
Existing Node.js installation
Installing Node.js
Global npm packages
Visual Studio Code
Installing Visual Studio Code
Docker
Installing Docker
Cloud services
Vercel Now
Google Firebase
Google Cloud
Amazon Web Services
Setup automation for Windows and macOS
PowerShell script
Bash script
The Angular CLI
Setting up your development directory
Generating your Angular application
Installing the Angular CLI
Initializing your Angular app
Publishing a Git repository using GitHub Desktop
Inspecting and updating package.json
Committing code using VS Code
Running your Angular app
Verifying your code
Optimizing VS Code for Angular
Configuring your project automatically
VS Code auto save
IDE settings
IDE extensions
Scripting code styling and linting
Configuring tooling
Implementing a style checker and fixer
Implementing a lint checker and fixer
Configuring Angular CLI autocomplete
VS Code Auto Fixer
Summary
Further reading
Questions
Creating a Basic Angular App
Planning using Kanban and GitHub projects
Setting up a GitHub project
Configuring a Kanban board
Creating a backlog for the Local Weather app
Wireframe design
High-level architecture
Crafting UI elements using components and interfaces
Adding an Angular component
Demystifying Angular components
Defining your model using interfaces
Using Angular Services and HttpClient to retrieve data
Creating a new Angular service
Injecting dependencies
Discovering OpenWeatherMap APIs
Storing environment variables
Implementing an HTTP GET operation
Retrieving service data from a component
Transforming data using RxJS
Implementing Reactive transformations
Null guarding in Angular
Property initialization
The safe navigation operator
Null guarding with *ngIf
Summary
Further reading
Questions
Automated Testing, CI, and Release to Production
Unit testing
Angular unit tests
Jasmine
Fixtures
Matchers
Anatomy of auto-generated unit tests
Unit test execution
Compilation errors
Test results
Configuring TestBed
Declarations
Providers
Imports
Test doubles
Fakes
Mocks, stubs, and spies
Angular e2e tests
e2e test execution
The e2e page object and spec
Production readiness
Building for production
Setting environment variables
Continuous Integration
CircleCI
GitHub flow
Deploying to the Cloud
Vercel Now
Deploying static files
Summary
Further reading
Questions
Delivering High-Quality UX with Material
Angular Material
Angular Material setup and performance
Installing Angular Material
Automatically
Manually
Understanding Material's components
Manually configuring Angular Material
Importing modules
Importing themes
Adding the Material Icon font
Angular Flex Layout
Responsive layouts
Installing Angular Flex Layout
Layout basics
Flex Layout APIs for DOM containers
Flex Layout APIs for DOM elements
Flex Layout APIs for any element
Using Material components
Angular Material schematics
Modifying the landing page with Material Toolbar
Material cards
Card header and content
Material typography
Applying typography
Flex Layout Align
Flex Layout
Implementing layout scaffolding
Aligning elements with CSS
Individually styling elements
Fine-tuning styles
Tweaking to match design
Custom themes
Unit testing with Material
Accessibility
Configuring automated pa11y testing
Building an interactive prototype
MockFlow WireframePro
Building a mock-up
Home screen
Search results
Settings pane
Adding interactivity
Exporting the functional prototype
Summary
Further reading
Exercises
Questions
Forms, Observables, and Subjects
Reactive forms 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
Exposé of a memory leak
Unsubscribing from a subscription
Unsubscribing using SubSink
Implementing the reactive style
Binding to an observable with an async pipe
Tapping into an observable stream
Multiple API calls
Implementing a postal code service
Chaining API calls
Summary
Exercises
Questions
Creating a Router-First Line-of-Business 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
Creating LemonMart
Creating a router-first app
Configuring Angular and VS Code
Configuring 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 browser manifest and icons
Custom themes
Custom icons
Material icons
Feature modules with lazy loading
Configuring feature modules with components and routes
Eager loading
Lazy loading
Completing the walking skeleton
The manager module
User module
POS and inventory modules
POS module
Inventory module
Inspect the router tree
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
Further reading
Questions
Designing Authentication and Authorization
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
Reusable services leveraging OOP concepts
JavaScript classes
Abstraction and inheritance
Create the auth service
Implement an abstract auth service
Abstract functions
Abstract caching service using localStorage
Caching the JWT
Implement an in-memory auth service
Simple login
Logout
Resuming a JWT session
HTTP interceptor
Dynamic UI components and navigation
Implementing the login component
Conditional navigation
Common validations for forms
UI service
Side navigation
Role-based routing using guards
Router guards
Auth guards
Auth service fake and common testing providers
Firebase authentication recipe
Add an application
Configure authentication
Implement Firebase authentication
Providing a service using a factory
Summary
Further reading
Questions
DevOps Using Docker
DevOps
Containerizing web apps using Docker
Anatomy of a Dockerfile
Installing Docker
Setting up npm scripts for Docker
Build and publish an image to Docker Hub
NPM scripts in VS Code
Docker extensions in VS Code
Deploying a Dockerfile to the cloud
Google Cloud Run
Configuring Docker with Cloud Run
Troubleshooting Cloud Run
Continuous deployment
Deploying to Vercel Now using CircleCI
Deploying to GCloud using orbs
Gated CI workflows
Advanced continuous integration
Containerizing build environments
Multi-stage Dockerfiles
Builder
Tester
Web server
CircleCI container-in-container
Code coverage reports
Code coverage in CI
Summary
Exercise
Further reading
Questions
RESTful APIs and Full-Stack Implementation
Full-stack architecture
Minimal MEAN
Angular
Express
Node
Mongo
Tooling
Configuring a monorepo
Monorepo structure
Git submodules
Configuring a Node project with TypeScript
CircleCI config
Docker Compose
Using Nginx as the web server
Containerizing the server
Configuring environment variables with DotEnv
Define Docker-Compose YAML
Orchestrating the Compose launch
Compose on CircleCI
RESTful APIs
API design with Swagger
Defining a Swagger YAML file
Preview Swagger file
Implementing APIs with Express.js
Bootstrapping the server
Routes and versioning
Services
Configuring Swagger with Express
MongoDB ODM with DocumentTS
About DocumentTS
Connecting to the database
Models with IDocument
Implementing JWT auth
Login API
Authenticating middleware
Custom server auth provider
GET User by ID
Generating users with Postman
Configuring Postman for authenticated calls
Postman automation
Put User
Pagination and filtering with DocumentTS
Summary
Exercise
Further reading
Questions
Recipes – Reusability, Routing, and Caching
Implementing a user service with GET
Implementing PUT with caching
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
Scaling architecture with reusable form parts
Base form component as an abstract class
Implementing a reusable form part
Input masking
Custom controls with ControlValueAccessor
Implementing a custom rating control
Using custom controls in forms
Layouts using grid list
Restoring cached data
Exercise
Summary
Further reading
Questions
Recipes – Master/Detail, Data Tables, and NgRx
Editing existing users
Loading data with resolve guard
Reusing components with binding and route data
Master/detail view auxiliary routes
Data table with pagination
Updating unit tests
NgRx Store and Effects
Implementing NgRx for LocalCast Weather
Comparing BehaviorSubject and NgRx
Setting up NgRx
Defining NgRx actions
Implementing NgRx Effects
Implementing reducers
Registering with Store using selector
Dispatching store actions
Unit testing reducers and selectors
Unit testing components with MockStore
NgRx Data
Implementing NgRx/Data in LemonMart
Configuring proxy in Angular CLI
Using Entity Service
Customizing Entity Service
Summary
Further reading
Questions
Highly Available Cloud Infrastructure on AWS
Creating a secure AWS account
Securing secrets
Right-sizing infrastructure
Optimizing instances
Simple load testing
Deploying to AWS ECS Fargate
Configuring ECS Fargate
Creating a Fargate cluster
Creating a container repository
Creating a task definition
Creating an elastic load balancer
Creating a cluster service
Configuring the DNS
Adding npm scripts for AWS
Publish
Deploying to AWS using CircleCI
AWS billing
Summary
Exercise
Further reading
Questions
Google Analytics and Advanced Cloud Ops
Collecting analytics
Adding Google Tag Manager to your Angular app
Setting up Google Tag Manager
Setting up Google Analytics
Budgeting and scaling
Calculating the per-user cost
Advanced load testing
Reliable cloud scaling
Cost per user in a scalable environment
Calculating target server utilization
Revising estimates with metrics
Measuring actual use
Creating a custom event
Adding custom events in Angular
Advanced analytics events
Summary
Further reading
Questions
Appendix A: Debugging Angular
The most useful shortcut
Troubleshooting errors in the browser
Leveraging Browser DevTools
Optimizing dev tools
Troubleshooting network issues
Investigating console errors
Karma, Jasmine, and unit testing errors
NetworkError
Generic ErrorEvents
Debugging with Dev Tools
Debugging with Visual Studio Code
Debugging with Angular Augury
Component Tree
Router Tree
NgModules
Debugging with Redux DevTools
Implement NgRx Console Logger
Configuring NgRx Store DevTools
Debugging RxJS
Tapping an RxJS Event Stream
Breakpoint debugging an RxJS Event Stream
Further advice
Appendix B: Angular Cheat Sheet
Built-in directives
Common pipes
Starter commands, major components, and CLI scaffolds
Starter commands
Major component scaffolds
TypeScript scaffolds
Common RxJS functions/operators
Functions
Operators
Further Reading
Another Book You May Enjoy
Index
Cover
Index
Welcome to the wonderful world of web development! This book has been designed to teach you the fundamentals of the Angular platform and equip you with useful recipes and practical code examples, so you can create rich and scalable line-of-business applications. The book emphasizes a minimalist approach, by maximizing the use of built-in libraries and avoiding the introduction of additional third-party dependencies to achieve the desired outcome. As a result of this approach, your code will be easier to maintain and upgrade, as new versions of Angular are released frequently. You may continue using this book as a learning resource, as the fundamental concepts, technologies, and samples included in the book will remain relevant for some time to come, albeit with slight modifications. The tools and services recommended in the book have been updated to their latest versions, circa 2020, however, tools and services continually evolve, change, and sometimes outright disappear. If and when this happens, feel free to reach out to me for alternatives.
This book will also aim to instill an Agile and DevOps mindset in you so that you confidently create reliable and flexible solutions. Whether you consider yourself a freelancer developing software for small businesses, a full-stack developer, an enterprise developer, or a web developer, what you need to know to design, architect, develop, maintain, deliver, and deploy a web application, and the best practices and patterns you need to apply to achieve those things, don't vary all that much. If you are delivering an application to an audience of users, in a sense, you are a full-stack developer, since you must be aware of a lot of server technologies. In fact, if you master how to deliver Angular applications using TypeScript, it won't be difficult for you to write your own RESTful APIs using Node.js, Express.js, and TypeScript, which is demonstrated through a concrete implementation later in the book.
By some definitions, a full-stack developer needs to know everything from catering to international copyright law to successfully create and operate an application on today's web. If you're an entrepreneur, in a sense, this is true. However, in this book, your culinary skills and law degrees need not apply. This book assumes that you already know how to work with web development basics and have familiarity working with RESTful APIs with the tech stack of your choice, and if not, fear not, just follow the hands-on step-by-step instructions and you will be able to create your first API-enabled Angular app in no time.
This book is for beginners and experienced developers alike who are looking to learn Angular or web development in general. If you are an Angular developer, you will 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. If you are a freelancer, you will pick up effective tools and technologies to deliver your Angular app in a secure, confident, and reliable way. If you're an enterprise developer, you will learn patterns and practices to write Angular applications with a scalable architecture.
Chapter 1, Introduction to Angular and Its Concepts, introduces the reader to the world of Angular and web development.
Chapter 2, Setting Up Your Development Environment, goes over a scriptable way to set up your environment.
Chapter 3, Creating a Basic Angular App, introduces the Kanban method of software development with easy-to-use design tools used to communicate ideas, going over Angular fundamentals, and leveraging CLI tools to maximize your impact.
Chapter 4, Automated Testing, CI, and Release to Production, covers unit testing, continuous integration, and rapid cloud deployments.
Chapter 5, Delivering High-Quality UX with Material, introduces you to Angular Material and explains how to use it to build great-looking apps.
Chapter 6, Forms, Observables, and Subjects, teaches you to become comfortable using Angular forms and reactive programming with RxJS.
Chapter 7, Creating a Router-First Line-of-Business App, focuses on the Router-first architecture, a seven-step approach to the design and development of mid-to-large line-of-business applications.
Chapter 8, Designing Authentication and Authorization, dives into authentication and authorization related patterns in Angular and RESTful applications.
Chapter 9, DevOps Using Docker, dives deep into containerization with Docker to enable repeatable development and operational workflows across diverse ecosystems.
Chapter 10, RESTful APIs and Full-Stack Implementation, walks you through the implementation of a real-world MEAN stack application to support line-of-business applications.
Chapter 11, Recipes – Reusability, Routing, and Caching, contains recipes around capturing and manipulating user data commonly needed for line-of-business applications.
Chapter 12, Recipes – Master/Detail, Data Tables, and NgRx, contains recipes around presenting user data commonly needed for line-of-business applications and an introduction to implementing the Flux pattern in Angular using NgRx.
Chapter 13, Highly Available Cloud Infrastructure on AWS, moves beyond application features to go over provisioning a highly-available cloud infrastructure on AWS.
Chapter 14, Google Analytics and Advanced Cloud Ops, goes over the nuances of owning, operating, and optimizing your cloud infrastructure, and using Google Analytics to capture user behavior.
Appendix A, Debugging Angular, covers how to deal with common Angular errors and breakpoint debugging using Chrome DevTools.
Appendix B, Angular Cheat Sheet, is a quick reference for Angular CLI commands, major Angular components, and common RxJS operators.
Appendix C, Keeping Angular and Tools Evergreen, includes detailed information about how to keep your development environment, Angular, and its dependencies up to date. You can read this appendix at https://static.packt-cdn.com/downloads/9781838648800_Appendix_C_Keeping_Angular_and_Tools_Evergreen.pdf. You can alternatively read this appendix at https://expertlysimple.io/stay-evergreen.
Appendix D, Self-Assessment Answers, has the answers to the test questions at the end of each chapter. You can read this appendix at https://static.packt-cdn.com/downloads/9781838648800_Appendix_D_Self-Assessment_Answers.pdf. You can alternatively read this appendix at https://expertlysimple.io/angular-self-assessment/.
You can get the latest version of the example code files for this book on GitHub. There are four projects that directly supports 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-serverIn each chapter you can find specific instructions to access chapter specific versions of code examples. When demonstrating continuous integration and continuous deployment configuration, Git branches and GitHub pull requests are utilized to demonstrate specific configuration elements.
You can download a snapshot of example code files for this book at the time of publishing from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at http://www.packtpub.com.Select the SUPPORT tab.Click on Code Downloads & Errata.Enter the name of the book in the Search box and follow the on-screen instructions.Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for LinuxThe code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Angular-for-Enterprise-Ready-Web-Applications-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/9781838648800_ColorImages.pdf.
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 Twitter 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/caskWindows 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 example, in menus or dialog boxes, also appear in the text like this. For example: "Browser vendors are supposed to implement these technologies as defined by the World Wide Web Consortium (W3C)."
Warnings or important notes appear like this.
Tips and tricks appear like this.
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 would report this to us. Please visit, http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
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.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
At first, there was HTML, then DHTML. Technologists invented new technologies like Java, JavaScript, PHP, and many others to deliver interactive experiences over the browser. The holy grail of programming was writing a program once and running it everywhere. In a flash, the era of Single-Page Applications (SPAs) was born. SPAs tricked the browser into thinking that a single index.html could house entire applications containing many pages. Backbone.js, Knockout.js, and Angular.js all came and went. Everyone reeling from unmanaged complexity and JavaScript-framework-of-the-week syndrome looked for a savior. Then came React, Angular, and Vue. They promised to fix all problems, bring about universally reusable web components, and make it easier to learn, develop, and scale web applications. And, so they did! Some better than others. 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.
This chapter covers:
The history of web frameworksAngular and the philosophy behind itThe reactive development paradigmAdvanced Angular features, including state managementMajor Angular releases and featuresThis first chapter is meant to give you a theoretical and historical background for the rest of the book. Feel free to use it as a reference as you go through the rest of the book. Chapter 2, Setting Up Your Development Environment, covers how you can configure your development environment for a great development experience. With Chapter 3, Creating a Basic Angular App, you begin implementing your first Angular application. If you're already experienced with Angular, you may start with Chapter 7, Creating a Router-First Line-of-Business App, to dive into creating scalable applications ready for the enterprise.
Each chapter in the book introduces you to new concepts and reinforces best practices while covering optimal ways of working with widely used and open source tools. Along the way, tips and information boxes cover the bases to close any knowledge gaps you may have about web and modern JavaScript development basics. As you go through the content, pay attention to numbered steps or bullet points as they describe actions you need to take. If you skip a section or a chapter, you may miss subtle changes in configuration or techniques that may confuse you later on.
The code samples provided in this book have been developed using Angular 9, which is planned to be in Long-Term Support (LTS) until August 2021. The chances are that you are reading this book after new versions have superseded Angular 9. However, worry not. This book adopts the Angular evergreen motto of always keeping the version of Angular up to date with the latest release. Keeping up to date is made possible by sticking to platform fundamentals and avoiding unnecessary third-party libraries. The example projects for the book were initially written for Angular 5 and updated over time without major rewrites by following a proactive and incremental Angular upgrade schedule. I anticipate these projects to survive with minor modifications for years to come. This reliability is a testament to the excellent compatibility work done by the Angular team.
The world of JavaScript, TypeScript, and Angular is constantly changing. It is normal for there to be some differences between code samples in the book and the code that is generated for you by the tools you use. For this reason, most of the best practices and configuration items recommended by this book are applied using tools that I created, so they can be updated. Below is a high-level overview of the collection of libraries, extensions, and open source projects that support the content of the book:
Figure 1.1: Code developed in support of this book
The preceding diagram is to give you a quick glance at some of the moving parts. Each component is detailed in the coming chapters. The most up-to-date versions of the sample code for the book are on GitHub, at the repositories linked below. These repositories contain the final and completed state of the code. To make it easier to verify your progress at the end of a chapter, the projects folder in each repository contains chapter-by-chapter snapshots reflecting the current state of the code:
For Chapters 2 to 6, and 12, LocalCast Weather: https://github.com/duluca/local-weather-appFor Chapters 7 to 14, Lemon Mart: https://github.com/duluca/lemon-martFor Chapter 10, Lemon Mart Server: https://github.com/duluca/lemon-mart-serverYou may read more about updating Angular in Appendix C, Keeping Angular and Tools Evergreen. You can find this appendix online from https://static.packt-cdn.com/downloads/9781838648800_Appendix_C_Keeping_Angular_and_Tools_Evergreen.pdf or at https://expertlysimple.io/stay-evergreen.
Let's take a look at the last 20 or so years of web development history, so you can contextualize how Angular came to be and evolved.
It is essential to consider why we use frameworks such as Angular, React, or Vue in the first place. Web frameworks came to rise 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 the vast majority of 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, which was successfully writing code that could manipulate the Document Object Model (DOM) of a browser consistently. Even the slightest difference in the APIs and capabilities of a browser would be enough to break a website.
In 2006, jQuery was developed to smooth out the differences between APIs and capabilities for browsers. 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 a good 5 to 6 years, jQuery became the web development framework. It was unimaginable to write an interactive website without using jQuery.
To create vibrant user experiences, however, 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 the complicated object graphs. Back in the 2000s, many users ran outdated browsers on relatively slow computers, so the user experience wasn't great.
Traditionally, software architecture is described in three primary layers, as shown in the diagram that follows:
Figure 1.2: Three-tiered software architecture
The presentation layer contains user interface (UI) related code, the business layer contains business logic, and the persistence layer contains code related to data storage. It is an overall design goal 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 that are 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. Modern web development has 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
In the preceding diagram, you can see an expanded architecture diagram that includes essential components of modern web development, which include an API layer that usually transforms data between the presentation and business layers, a tools and best practices layer that defines various methodologies used to develop the software, and an automated testing layer that is crucial in today's iterative and fast-moving development cycles.
In the 2000s, many internet companies 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 a sample 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 data that is needed, 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 a consistent user experience (UX) across its userbase. I find the combination of server-side rendering and MVC to be an intricate pattern to execute. 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, and that 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 co-mingle presentation and business logic in such implementations unintentionally. When this happens, the inevitable UI modernization of an otherwise well-functioning system becomes impossible. Put in other terms, to replace the sink in your kitchen with a new one, you must renovate your entire kitchen. Due to insufficient architecture, organizations routinely spend millions of dollars every 10 years writing and rewriting the same applications.
During the 2000s, it was possible to build rich web applications that were 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 out of date, 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 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 to them and do so in a seemingly cost-effective way. The diagram that follows 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, then we can architecturally enforce the implementation of presentation and business logic separately. In theory, this RESTful web services pattern should allow us to replace the kitchen sink as often as we want to without having to remodel the entire kitchen.
Figure 1.5: Rich-client decoupled MVVM architecture
Observe the near doubling of boxes in the preceding diagram. Just because we separate the client from the server, we don't end up simplifying the architecture. If anything, the architecture surrounding the presentation logic becomes a lot more complicated. Both 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 own 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 down to the client to avoid such problems. Newer technologies like GraphQL go a step 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 it was viable to create web applications that run natively in the browser. All SPA frameworks at the time relied on jQuery for DOM manipulation. Meanwhile, web standards continued to evolve, and evergreen browsers that support new standards started to become commonplace. However, change is constant, and the evolution of web technologies made it unsustainable to evolve this first generation of SPA frameworks gracefully.
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.
Angular is an open source project maintained by Google and a community of developers. The new Angular platform is vastly different from the legacy framework you may have used in the past. 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 versions of Angular, versions in the 1.x.x range, are referred to as AngularJS. Version 2.0.0 and higher versions are called Angular. Where AngularJS is a monolithic JavaScript SPA framework, Angular is a platform that is capable of targeting browsers, hybrid-mobile frameworks, desktop applications, and server-side rendered views.
Upgrading to the new AngularJS was risky and costly because even minor updates introduced new coding patterns and experimental features. Each update introduced deprecations or the refactoring of old features, which required rewriting 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 likely were 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 planned end-of-life in July 2021.
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 second next 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 AngularJS and Angular:
Figure 1.6: Tentative Angular release and support schedule
So, what does this mean for you? You can be confident that your Angular code is supported and backward compatible for an approximate time frame of 24 months, even if you make no changes to it. So, if you wrote an Angular app in version 9 in February 2020, your code is runtime compatible with Angular 10 and will be supported until October 2021. To upgrade your Angular 9 code to Angular 11, you need to ensure that you're not using any of the deprecated APIs that receive a deprecation notice in Angular 10.
In practice, most deprecations are minor and are straightforward to refactor. Unless you are working 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.
You may think Google has infinite resources to update thousands of app regularly. Like any organization, Google too has limited resources, and not every app is actively maintained by a dedicated team. So, the Angular team must ensure compatibility through automated tests and make it as painless as possible to move through major releases going forward. In Angular 6, the update process was made much simpler with the introduction of ng update.
The Angular team continually improves its release process with automated CLI tools to make upgrades of deprecated functionality a mostly automated, reasonable endeavor. The benefits of this strategy were demonstrated by Air France and KLM being able to reduce 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 alike. 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 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 is a demonstration of technical prowess, which retains and attracts developer talentAn open source framework enables the proving and debugging of new ideas and tools with millions of developers at scaleAllowing developers to create great web experiences more quickly, ultimately drives more business for Google and MicrosoftI 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 note that sometimes Angular is referred to as Angular 2 or Angular 4. At times, both Angular and AngularJS are referred to as AngularJS. This is incorrect. The documentation for Angular is at angular.io. If you land on angularjs.org, you'll be reading about the legacy AngularJS framework.
For the latest updates on the upcoming Angular releases, view the official release schedule at https://angular.io/guide/releases.
Your time is valuable, and your happiness is paramount, so you must be careful in choosing the technologies to invest your time in. With this in mind, we need to answer the question of why learn Angular, but not React, Vue, or some other framework? 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 frameworks, with their strengths and weaknesses. Every tool has its place and purpose.
In some cases, React is the right choice for a project, and in other cases, Vue is the right one. Regardless, 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, then you must abide by the prime directive; keep business logic implemented behind the API decoupled from 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 the deprecation of 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. Convention-based frameworks, although they may seem elegant from the outside, make it difficult for newcomers to pick up the framework. Configuration-based frameworks, however, 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. Angular, through its various mechanisms, enables the proper execution of these concepts. It gets rid of 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 go over Angular's evergreen mindset and the reactive programming paradigm, which are the latest extensions of Angular's initial philosophy.
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 with the idea of deemphasizing 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, I can affirm that you can depend on Angular as a mature web development platform. Angular frequently receives updates with great attention to backward compatibility. Furthermore, any code that is made incompatible by a new version is brought forward with help from automated tools or explicit guidance on how to update your code via update.angular.io, 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.
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 that are labeled next are meant for early adopters and for testing the compatibility of your code 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 providing support for older browsers, so your code can reach the widest audience possible.
Angular is coded using TypeScript. TypeScript was created by Anders Hejlsberg of Microsoft to address several major issues with applying JavaScript at the enterprise-scale.
Anders Hejlsberg is the creator of Turbo Pascal and C#, and is the chief architect of Delphi. 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 code you write is parsed and understood by the browser 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. It is much cheaper to detect and fix bugs at compile time versus runtime. TypeScript brings the benefits of statically typed languages to JavaScript by introducing types and generics to the language. However, TypeScript does not include a compilation step, but instead a transpilation step. A compiler builds code into machine language with C/C++ or intermediary language (IL) with Java or C#. A transpiler, however, merely translates 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 feature set and the syntax of the language is 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. Starting with the introduction of ES5 and then ES2015 (also known as ES6), browser vendors have struggled to implement new JavaScript features within their browsers. 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 a sliding one, as TC39 has committed to updating JavaScript every year going forward. As a result, TypeScript represents the past, present, and future of JavaScript. 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.
Now, let's go over Angular's underlying architecture.
Angular follows the MV* pattern, which is 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 have to 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 is the combination of a JavaScript class written in TypeScript and an Angular template written in HTML, CSS, and TypeScript. 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 are going to improve your understanding of how Angular works vastly. 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 having to worry about the order of instantiation, initialization, or destruction of such objects from memory.
Angular templates also allow similar reuse of code 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.
All Angular components, services, directives, pipes, and user controls are organized under modules. Each Angular app is bootstrapped by a root module that renders your first component and injects any services and prepares dependencies it may require. You may introduce children modules to enable capabilities like lazy loading so that you don't have to deliver all components of your web application to the browser all at once. For instance, there is no use sending code for the admin dashboard to a user without admin privileges.
Angular makes heavy use of the RxJS library, which introduces reactive development patterns to Angular, as opposed to more traditional imperative development patterns.
Angular supports multiple styles of programming. The plurality of coding styles is one of the great reasons why it is approachable to programmers with varying backgrounds. Whether you come from an object-oriented programming background or you're a staunch believer of functional programming, you can build viable apps using Angular. In Chapter 3, Creating a Basic Angular App, you'll begin leveraging reactive programming concepts in building the LocalCast Weather app.
As a programmer, you are most likely used to imperative programming. Imperative programming is when you, as the programmer, write sequential code describing everything that must be done in the order that you've defined them and the state of your application depending on just the right variables to be set to function correctly. You write loops, conditionals, and call functions; you fire off events and expect them to be handled. Imperative and sequential logic is how you're used to coding.
