27,99 €
Single page applications (SPAs) have become the standard for most web experiences. Angular, with its batteries-included approach, has emerged as a powerful framework for simplifying the development of these interfaces by offering a comprehensive toolbox. This book guides you through the Angular ecosystem, uncovering invaluable design patterns and harnessing its essential features.
The book begins by laying a strong foundation, helping you understand when and why Angular should be your web development framework of choice. The next set of chapters will help you gain expertise in component design and architecting efficient, flexible, and high-performing communication patterns between components. You’ll then delve into Angular's advanced features to create forms in a productive and secure way with robust data model typing. You'll also learn how to enhance productivity using interceptors to reuse code for common functionalities, such as token management, across various apps. The book also covers micro frontend architecture in depth to effectively apply this architectural approach and concludes by helping you master the art of crafting tests and handling errors effortlessly.
By the end of this book, you'll have unlocked the full potential of the Angular framework.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 273
Veröffentlichungsjahr: 2024
Angular Design Patterns and Best Practices
Create scalable and adaptable applications that grow to meet evolving user needs
Alvaro Camillo Neto
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.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Kushal Dave
Book Project Manager: Shagun Saini
Senior Editor: Rakhi Patel
Technical Editor: K Bimala Singha
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Ponraj Dhandapani
DevRel Marketing Coordinators: Namita Velgekar and Nivedita Pandey
First published: February 2024
Production reference: 2120124
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-83763-197-1
www.packtpub.com
To my wife, Luciana Gonçalo Balardini Camillo, for being my wonderful beloved partner who did the most important work of taking care of our beloved children, Mario and Gabriel, while I worked on the book. I love you so much my Linda.
– Alvaro Camillo Neto
In the ever-evolving landscape of the web, Angular continues to emerge as a beacon of innovation and efficiency, in a continual era of renaissance, and I am thrilled to introduce you to a comprehensive guide authored by a true enthusiast and expert, Alvaro.
This book is a testament to Alvaro’s tireless efforts to share his knowledge in the most exciting and up-to-date manner possible. Whether you are a seasoned developer seeking to sharpen your skills or a newcomer eager to dive into the world of Angular, this guide promises to be your trusted companion.
So, embark on this adventure with this book as your guide. May the knowledge within these pages inspire you and empower your journey into the universe of web development, with batteries included for this awesome JavaScript framework, which will always have a module and patterns for what you need.
Happy coding!
William Grasel (https://www.linkedin.com/in/willgm/?originalSubdomain=br)
Principal Software Engineer, Stone Inc
With great excitement and admiration, I write this foreword for my dear friend Alvaro’s book, Angular Design Patterns and Best Practices. For anyone familiar with the Angular framework and seeking to elevate their skills and projects, this book is an invaluable resource.
Alvaro, a Google Developer Expert in Angular and a friend, has poured his wealth of knowledge and practical experience into this comprehensive guide. In Part 1, Reinforcing the Foundations, he skilfully navigates essential topics, starting by reinforcing the foundations of Angular development by delving into project setup, application organization, TypeScript patterns, and service implementation, including the Singleton pattern.
Then, Part 2, Leveraging Angular’s Capabilities equips you with advanced techniques to handle user input through forms, enhance backend integration through the Interceptor pattern, and master reactivity with RxJS. This section empowers developers to create dynamic and interactive experiences for their users.
In the final stretch, that is, Part 3, Architecture and Deployment, Alvaro delves into designing applications for testability, exploring the possibilities of micro-frontends with Angular elements, and sharing best practices for deployment. This part lays the groundwork for robust, scalable, and maintainable applications.
Finally, the Angular Renaissance chapter paints a vibrant picture of the future of modern Angular applications, highlighting the latest advancements and trends shaping the framework. This glimpse into the future inspires and motivates developers to stay ahead of the curve and continually improve their craft.
Alvaro’s writing style is clear, concise, and engaging. He seamlessly blends theoretical concepts with practical examples, making even the most complex topics easily understandable. Additionally, his passion for Angular shines through every page, further igniting your desire to delve deeper into the framework’s capabilities.
So, buckle up, fellow Angular enthusiast, and prepare to embark on a journey of knowledge and growth. With Alvaro as your guide, you’ll be crafting elegant, robust, and future-proof Angular applications in no time.
Happy coding!
Loiane Groner
Published Author and Vice-President – Software Development at CitiBank
Alvaro Camillo Neto is a software engineer, speaker, and instructor in Brazil. He has worked in the technology industry for over 10 years and is dedicated to the development of business solutions at a large company. Alvaro is a technology enthusiast, and he sees knowledge sharing as an opportunity to help the community that helped him so much and the best way of learning. He believes in technology as a tool to empower people. He has performed at small meetups and large events, focusing on the themes of developing web solutions. He also shares knowledge on his blog (https://alvarocamillont.dev/) and participates in the organization of AngularSP.
Anu Nagan G has worked at various corporate organizations, starting at a SaaS startup (GenDeep) and moving on to midsize (GAVS) and Fortune 500 companies (DXC). There, he had various roles, such as technical product manager, full stack product lead (in Angular, Java, Python, and AWS), and delivery lead, respectively, in his 10.3 years of tenure. Currently, he is with Bounteous as a technical manager, leading global delivery projects such as migrating legacy WordPress apps to Adobe AEM. Prior to that, he led parallel projects, such as the advanced AI and analytics product CortexAI, clinical mobile app development, and Salesforce automation into B2B business. He previously contributed to various AIOps products, such as ZIF and Gcare. He is an avid reader and cinephile, loves to play guitar, and makes short films with his friends.
I would like to thank my wife and daughter, A Chekhov H, who celebrated her first birthday on 21 December, 2023.
The Angular framework has been helping development teams since 2009, with a robust structure and practically everything a web application needs. Angular, with its “batteries included” philosophy, has mechanisms for state management, route administration, and the injection of dependencies among other tools for you to create the most incredible experiences for your users.
This book aims to help you navigate this incredible list of features and learn how to orchestrate it for you and your team to get the most out of Angular and its entire ecosystem.
We will discover what types of patterns exist in the framework and what lessons we can learn from these patterns to apply to our applications.
We will also explore Angular development and architecture best practices based on its documentation, and community advice around the Angular ecosystem.
Angular is widely used by companies of different sizes and sectors. The company that sponsors this open source framework, Google, has thousands of internal applications that use Angular, guaranteeing great stability, which is one of the biggest reasons for using it.
There is a huge demand for developers who have mastered Angular and architects who can organize and get the best out of Angular, and the framework is currently in its best form, dubbed by the community as the Angular Renaissance.
This book is for frontend developers and architects with experience in Angular or any other web framework who want to delve into the best that Angular can offer.
The main personas that this book is aimed toward are the following:
Developers who already work with Angular and want to be more productive in delivering their tasksTechnical leaders who want to bring best practices to their teams to increase the quality and productivity of their deliveriesSoftware architects who want to explore the possibilities that Angular can offer applications and thus design resilient and secure systemsChapter 1, Starting Projects the Right Way, reinforces the fundamentals of Angular, its principles, and how to configure your project and development environment to be as productive as possible.
Chapter 2, Organizing Your Application, explores best practices in organizing an Angular project and how to optimize your application’s performance by lazy loading Angular modules.
Chapter 3, TypeScript Patterns for Angular, delves into the framework’s base language, TypeScript, and helps you understand why it was chosen by the Angular team and how we can apply to our projects.
Chapter 4, Components and Pages, works with the base element of the framework, the component, and how we can structure our project to create concise and efficient applications.
Chapter 5, Angular Services and the Singleton Pattern, analyzes Angular services to separate business logic from presentation logic and best practices for communicating with the backend.
Chapter 6, Handling User Inputs: Forms, is where we will study the main way users interact with our applications, through forms, and how we can create reactive and easy-to-maintain forms.
Chapter 7, Routes and Routers, is where we will work with Angular’s routing mechanism and how to manage our applications’ routes in a secure and optimized way.
Chapter 8, Improving Backend Integrations: the Interceptor Pattern, is where we will apply the Interceptor design pattern to common tasks when dealing with backend communication, such as token management and user notification.
Chapter 9, Exploring Reactivity with RxJS, delves deeper into the RxJS library and how we can make the most of it for managing information flows and interactions in our projects.
Chapter 10, Design for Tests: Best Practices, discusses automated testing and how to prepare our project for this process, as well as exploring unit testing with the Jasmine and Karma libraries and end-to-end testing with the open source tool Cypress.
Chapter 11, Micro Frontend with Angular Elements, explores the micro frontend architecture and discusses when to use it and how to implement it in Angular using the Angular Elements library.
Chapter 12, Packaging Everything: Best Practices for Deployment, looks at the best practices for building and deploying our Angular applications to cloud environments. Using an example project, we will explore the Microsoft Azure cloud.
Chapter 13, The Angular Renaissance, explores how to keep ourselves and our applications up to date with the constant evolution of Angular and looks at incredible features such as Angular Signals, standalone components, and lazy loading components using the defer instruction.
You will need to have a basic understanding of HTML, CSS, and JavaScript and how a web application works.
Software/hardware covered in the book
Operating system requirements
Angular 16 and 17
Windows, macOS, or Linux
TypeScript 5.2
RxJS 7
Azure
You can download the example code files for this book from GitHub at . If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “In this test case, we don't need to worry about the login because the beforeEach function performs this function and we work directly on the form.”
A block of code is set as follows:
describe('My First Test', () => { it('Visits the initial project page', () => { cy.visit('/') cy.contains('app is running!') }) })When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
<button type="submit" class="w-full rounded bg-blue-500 px-4 py-2 text-white" [disabled]="loginForm.invalid" [class.opacity-50]="loginForm.invalid" data-cy="submit" > Login </button>Any command-line input or output is written as follows:
ng testBold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Select the desired browser and click on Start E2E Testing and we will have the test execution interface.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
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 www.packtpub.com/support/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 authors.packtpub.com.
Once you’ve read From PHP to Ruby on Rails, 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.
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 belowhttps://packt.link/free-ebook/9781837631971
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyIn this part you will delve deeper into the fundamentals of the Angular framework and its basic concepts such as why to use Angular, how to organize your project and set up a productive development environment. In addition, you will learn about best practices in the tasks of component creation and communication with the backend.
This part has the following chapters:
Chapter 1, Starting Projects the Tight WayChapter 2, Organizing Your ApplicationChapter 3, TypeScript Patterns for AngularChapter 4, Components and PagesChapter 5, Angular Services and the Singleton PatternAngular is a framework that has the motto “batteries included” as a development philosophy. This means that practically all the resources you need for your frontend application needs are already available as soon as you create a new project.
In this chapter, you will understand why choose Angular for your web application, what its main characteristics and design are, and why companies, especially the biggest ones, choose Angular as the main framework for developing single-page applications.
You will explore the technologies that make up the framework and thus take greater advantage of possible alternatives if you need them for a specific case. You’ll also set up your workspace with the best tools to help you and your team’s productivity.
In this chapter, we’re going to cover the following topics:
Why choose Angular?What technologies are present in the ecosystem?Configuring your development environmentStarting an Angular projectUsing the Angular Command-Line Interface (CLI) for your productivityBy the end of this chapter, you will have arguments for using Angular in your project and be more productive in your development workspace.
To follow the instructions in this chapter, you’ll need the following:
Visual Studio Code (VS Code) (https://code.visualstudio.com/Download)Node.js 18 or higher (https://nodejs.org/en/download/)The code files for this chapter are available at .
The choice of technology to be used in a given project is critical to its success. You, as a project developer or architect, must help your team in this mission by choosing the best tool for the job.
The Angular framework is one of the most used tools for building a single-page application, along with React and Vue. When choosing the right tool for the job, you need to answer why.
The following are some arguments for choosing Angular.
Angular is an opinionated framework, which means that the Angular development team has already made several choices of tools and solutions for every challenge that a web application can have. This way, you and your team don’t have to research which route engine or state management library you should use; it’s all included and configured for your project.
This feature also simplifies the onboarding of new developers in your team. Following the guidelines proposed by the documentation and using the best practices, Angular projects usually have the same structure and method of development. Knowing Angular you can quickly locate yourself in any ongoing project.
Angular was created and maintained by the Angular team at Google. Although excellent frameworks such as Vue.js and Svelte are maintained only by their communities, having such a big tech company supporting the framework brings security to the choice of technology, especially for large companies.
In addition, Angular is used in more than 300 internal applications and Google products, which means stability and quality because, before each new version of the framework is released, it is validated in all these applications.
The Angular team has strived since version 13 to increase transparency within the community by releasing a roadmap (https://angular.io/guide/roadmap) detailing all the improvements in progress and what to expect for the future of the framework, giving you peace of mind that it will be supported for years to come.
Technology is only as alive as the community that supports it, and Angular has a huge one. Meetups, podcasts, events, articles, and videos – the Angular community has many resources to help developers.
The people who make up this community also have the important contribution of giving feedback, creating and correcting issues in Angular. As it is an open source project, everyone is invited to evaluate and contribute to the code.
The Angular team also asks the community for help with major framework decisions through Requests for Comment (RFCs).
In addition, the community creates many libraries that expand the possibilities of the framework, such as NgRx (https://ngrx.io/) for advanced state management and Transloco (https://ngneat.github.io/transloco/) to support internationalization, among others.
One of the differentiating factors of Angular compared to its competitors is the focus from the beginning on tooling and developer experience. The Angular CLI tool is a powerful productivity tool that we will explore in this chapter, which is used far beyond the simple creation and setup of a project.
From a testing point of view, Angular is already equipped and configured with Karma as a test runner and Jasmine as a configuration tool. Angular’s tooling already configures the project build using webpack and already has a dev server.
The tool is also extensible, allowing the community to create routines for configuring and updating their libraries.
With these arguments, you will be able to base your choice of Angular on your project; let’s see now which technologies make up the framework’s ecosystem.
The Angular team, when creating the solution for the growing complexity of web application development, decided to unite the best tools and libraries in an opinionated package with the maximum number of configurations made by default.
We then have the following libraries that make up the core of Angular.
TypeScript is a superset of the JavaScript language that adds type checking and other features to the language, ensuring a better developer experience and security for web development.
It has been present in Angular since its first version and is the cornerstone of the framework that enables several features such as dependency injection, typed forms and Angular’s tooling.
TypeScript is currently the preferred tool for backend development in Node.js and is encouraged by communities of other frameworks such as React and Vue.js.
RXJS is a library that implements the reactive paradigm (https://www.reactivemanifesto.org/) in theJavaScript language.
Since the first version of Angular, reactivity was a core theme that the framework wanted to achieve and so it uses the RXJS library to help with it.
HTTP requests, routes, forms, and other Angular elements use the concepts of observables and their operators to provide Angular developers with the tools to create more fluid and dynamic applications with less boilerplate code.
RXJS also provides mechanisms for state management in a frontend application without the need to use more complex patterns such as Redux.
Quality should be the top priority in any application and this is especially important in frontend applications as for the user, it is the application.
One of the ways to attest to quality is through testing, and with that in mind, Angular already comes by default with the tool duo of Jasmineand Karma.
Jasmine is a framework for unit-testing JavaScript and TypeScript applications with several functions for assertion and test assembly.
Karma is the test runner, that is, the environment where the unit test setup is executed with the help of Jasmine. This environment, configured in its configuration file, runs in browsers, making the test more realistic in comparison to customers’ daily lives.
Many people in the community switch these tools for the Jest framework due to performance in the execution of the tests, which is totally fine and even facilitated by the Angular CLI; however, it should be noted that this tool does not run in a browser, which really improves the performance of the test execution but may hide some particularity that only testing in a browser would provide.
After the development of an application, it is necessary to create the bundle to send it to production, and Webpack is the tool that the Angular team chose for this task.
Webpack is a very powerful and versatile bundler, and it is thanks to it that the framework manages to make some interesting optimizations such as tree shaking and lazy loading of bundles.
However, Webpack is complex in its configuration, and with that in mind, the Angular team has already set up and created some abstractions for fine-tuning the tool, such as the angular.json file.
We understand what pieces make up the framework and how they relate to delivering rich and fluid interfaces. We will now set up our development environment.
A well-organized environment with the right tools is the first step toward excellence and productivity; now, let’s set this environment up in your workspace.
After installing Node.js following the instructions in the Technical requirements section, the following tools and their plugins will help you in your workflow.
VS Code (https://code.visualstudio.com/) is currently the default tool for most developers, especially for frontend projects.
There are other very good ones such as WebStorm (https://www.jetbrains.com/webstorm), but VS Code, with its plugins especially for Angular projects, facilitates great productivity and ergonomics.
To install the plugins listed here, in the code editor, click on Extensions or use the shortcut Ctrl + Shift + X (Windows) or Cmd + Shift + X (macOS).
The following are the VS Code plugins recommended for developing Angular applications.
Git Extension Pack (https://marketplace.visualstudio.com/items?itemName=donjayamanne.git-extension-pack) is not specifically for developing Angular applications but it is useful for any kind of work.
Git is the default tool for version control and VS Code has native support for it. This set of plugins improves this support even further, adding the ability to read comments and changes made in previous commits in the editor, support for multiple projects, and a better view of your repository history and logs.
The Angular Language Service (https://marketplace.visualstudio.com/items?itemName=Angular.ng-template) extension is maintained by the Angular team and adds support for most of the framework’s functionality right from the code editor.
By adding this extension to your editor, it will have the following features:
Autocomplete in the HTML template file, allowing you to use component methods without having to consult the TypeScript fileChecking for possible compilation errors in HTML template files and TypeScript filesQuick navigation between HTML and TypeScript templates, allowing you to consult the definition of methods and objectsThis extension is also available for other IDEs such as WebStorm and Eclipse.
Prettier (https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) is a JavaScript tool that solves the code formatting problem. It is opinionated on formatting settings although some customization is possible.
In addition to TypeScript, Prettier formats HTML, CSS, JSON, and JavaScript files, making this extension useful also for backend development using Node.js.
To standardize formatting across your entire team, you can install Prettier as a package for your project and run it on the project’s CI/CD track, which we’ll see in Chapter 12, Packaging Everything – Best Practices for Deployment.
When creating an application, the use of a linter is highly recommended to ensure good language practices and avoid errors from the beginning of development.
In the past, the default tool for linting TypeScript projects was TSLint, but the project has been absorbed by ESLint (https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint), which allows you to verify JavaScript and TypeScript projects.
With this extension, verification occurs quickly while you type the code of your project. ESLint can be installed as a package in your Angular project and thus performs this validation on the CI/CD conveyor of your project, which we will see in Chapter 12, Packaging Everything – Best Practices for Deployment.
The EditorConfig (https://marketplace.visualstudio.com/items?itemName=EditorConfig.EditorConfig) plugin has the function of creating a default configuration file for not only VS Code but also any IDE that supports this format.
This plugin is useful for standardizing things for your project and your team – for example, the number of spaces that each Tab key represents, or whether your project will use single quotes or double quotes to represent strings.
To use it, just create or have a file named .editorconfig at the root of your project and VS Code will respect the settings described in the file.
VS Code, in addition to extensions, has several native settings that can help in your day-to-day work. By accessing the File menu, we can activate the automatic saving flag so you don’t have to worry about pressing Ctrl + S all the time (although this habit is already engraved in stone in our brains...).
Another interesting setting is Zen mode, where all windows and menus are hidden so you can just focus on your code. To activate it, go to View | Appearance | Zen Mode, or use the keyboard shortcut Ctrl + K + Z for Windows/Linux systems and Cmd + K + Zfor macOS.
To improve the readability of your code during editing, an interesting setting is Bracket coloring, which will give each parenthesis and bracket in your code a different color.
To enable this setting, open the configuration file using the shortcut Ctrl + Shift + P for Windows/Linux or Cmd + Shift + P for macOS and type Open User Settings (JSON).
In the file, add the following elements:
{ "editor.bracketPairColorization.enabled": true, "editor.guides.bracketPairs": true }VS Code also has the Inlay Hints feature, which shows details of parameter types and return methods, as well as other useful information on the line you are reading in the code.
To configure it in the Settings menu, look for Inlay Hints and activate it if it is not already configured. For the development of your Angular application, you can also perform specific configurations by selecting TypeScript.
It is also possible to turn on this functionality by directly configuring the settings.json file with the following elements:
{ "typescript.inlayHints.parameterNames.enabled": "all", "typescript.inlayHints.functionLikeReturnTypes.enabled": true, "typescript.inlayHints.parameterTypes.enabled": true, "typescript.inlayHints.propertyDeclarationTypes.enabled": true, "typescript.inlayHints.variableTypes.enabled": true, "editor.inlayHints.enabled": "on" }An important detail that not every developer pays attention to is the type of font they use in their code editor. A confusing font can make it difficult to read code and tire your eyes.
The ideal option is to use monospaced fonts, that is, fonts where the characters occupy the same horizontal space.
A very popular font is Fira Code (https://github.com/tonsky/FiraCode), which, in addition to being monospaced, has ligatures for programming – that is, joining or changing characters that represent symbols such as , >=, and =>, as shown in the following figure:
Figure 1.1 – Example of symbols with font ligatures
After installing the font on your operating system, to enable ligatures in the font in VS Code, access the configuration