Book Image

ASP.NET Core 6 and Angular - Fifth Edition

By : Valerio De Sanctis
Book Image

ASP.NET Core 6 and Angular - Fifth Edition

By: Valerio De Sanctis

Overview of this book

Every full-stack ninja needs the tools to operate on front-end and back-end application development. This web app development book takes a hands-on, project-based approach to provide you with all the tools and techniques that web developers need to create, debug, and deploy efficient web applications using ASP.NET Core and Angular. The fifth edition has been updated to cover advanced topics such as Minimal APIs, Web APIs with GraphQL, real-time updates with SignalR, and new features in .NET 6 and Angular 13. You begin by building a data model with Entity Framework Core, alongside utilizing the Entity Core Fluent API and EntityTypeConfiguration class. You'll learn how to fetch and display data and handle user input with Angular reactive forms and front-end and back-end validators for maximum effect. Later, you will perform advanced debugging and explore the unit testing features provided by xUnit.net (.NET 6) and Jasmine, as well as Karma for Angular. After adding authentication and authorization to your apps, you will explore progressive web applications, learning about their technical requirements, testing processes, and how to convert a standard web application to a PWA. By the end of this web development book, you will understand how to tie together the front-end and back-end to build and deploy secure and robust web applications.
Table of Contents (18 chapters)
16
Other Books You May Enjoy
17
Index

What’s new in Angular?

If following in the footsteps of Microsoft and the .NET Foundation in recent years has not been an easy task, things were not going to get any better when we turned our eyes to the client-side web framework known as Angular. To understand what happened there, we have to go back 10 years, to when JavaScript libraries such as jQuery and MooTools were dominating the client-side scene; the first client-side frameworks, such as Dojo, Backbone.js, and Knockout.js, were struggling to gain popularity and reach wide adoption; and stuff such as React and Vue.js didn’t even exist.

Truth be told, jQuery is still dominating the scene to a huge extent, at least according to BuiltWith (https://trends.builtwith.com/javascript/javascript-library) and w3Techs (https://w3techs.com/technologies/overview/javascript_library/all). However, despite being used by 74.1% of all websites, it’s definitely an option chosen less often by web developers than it was 10 years ago.

GetAngular

The story of AngularJS started in 2009 when Miško Hevery (now senior computer scientist and Agile coach at Google) and Adam Abrons (now director of engineering at Grand Rounds) were working on their side project, an end-to-end (E2E) web development tool that would have offered an online JSON storage service and also a client-side library to build web applications depending on it. To publish their project, they took the GetAngular.com hostname.

During that time, Hevery, who was already working at Google, was assigned to the Google Feedback project with two other developers. Together, they wrote more than 17,000 lines of code in 6 months, slowly sinking into a frustrating scenario of code bloat and testing issues. Given the situation, Hevery asked his manager to rewrite the application using GetAngular (the side project mentioned previously), betting that he could do that alone within 2 weeks. His manager accepted and Hevery lost the bet shortly thereafter, as the whole thing took him 3 weeks instead of 2; however, the new application had only 1,500 lines of code instead of 17,000. This was more than enough to get Google’s interest in the new framework, which was given the name AngularJS shortly thereafter.

To listen to the full story, take a look at the following Miško Hevery keynote speech at ng-conf 2014: https://www.youtube.com/watch?v=r1A1VR0ibIQ.

AngularJS

The first stable release of AngularJS (version 0.9.0, also known as dragon-breath) was released on GitHub in October 2010 under an MIT license; when AngularJS 1.0.0 (also known as temporal domination) came out in June 2012, the framework had already achieved huge popularity within the web development communities worldwide.

The reasons for such extraordinary success can hardly be summarized in a few words, but I’ll try to do that nonetheless by emphasizing some key selling points:

  • Dependency injection: AngularJS was the first client-side framework to implement it. This was undeniably a huge advantage over the competitors, including DOM-manipulating libraries such as jQuery. With AngularJS, developers could write loosely coupled and easily testable components, leaving the framework with the task of creating them, resolving their dependencies, and passing them to other components when requested.
  • Directives: These can be described as markers on specific DOM items such as elements, attributes, and styles: a powerful feature that could be used to specify custom and reusable HTML-like elements and attributes that define data bindings and/or other specific behaviors of presentation components.
  • Two-way data binding: The automatic synchronization of data between model and view components. When data in a model changes, the view reflects the change; when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view are updated at all times.
  • Single-page approach: AngularJS was the first framework to completely remove the need for page reloads. This provided great benefits at both the server-side (fewer and smaller network requests) and client-side level (smoother transitions, a more responsive experience), and paved the way for the single-page application pattern that would also be adopted by React, Vue.js, and the other runner-up frameworks later on.
  • Cache-friendly: All the AngularJS magic was meant to happen on the client side, without any server-side effort to generate the UI/UX parts. For this very reason, all AngularJS websites could be cached anywhere and/or made available through a CDN.

For a detailed list of AngularJS features, improvements, and bug fixes from 0.9.0 through 1.7.8, check out the following link:

Angular 2

The new release of AngularJS, released on September 14, 2016, and known as Angular 2, was a complete rewrite of the previous one, entirely based upon the new ECMAScript version 6 (officially ECMAScript 2015) specifications. Just like the ASP.NET Core rewrite, the revolution brought such a number of breaking changes at the architectural level and for HTTP pipeline handling, the app life cycle, and state management that porting the old code to the new one was nearly impossible. Despite keeping its former name, the new Angular version was a brand-new framework with little or nothing in common with the previous one.

The choice to not make Angular 2 backward-compatible with AngularJS clearly demonstrated the intention of the author’s team to adopt a completely new approach, not only in the code syntax but also in their way of thinking and designing the client app. The new Angular was highly modular, component-based, and came with a new and improved dependency injection model and a whole lot of programming patterns its older cousin had never heard of.

Here’s a brief list of the most important improvements introduced with Angular 2:

  • Semantic versioning: Angular 2 is the first release to use semantic versioning, also known as SemVer: a universal way of versioning the various software releases to help developers track down what’s going on without having to dig into the changelog details. SemVer is based on three numbers – X.Y.Z, where X stands for a major version, Y stands for a minor version, and Z stands for a patch release. More specifically, the X number, representing the major version, gets incremented when incompatible API changes are made to stable APIs; the Y number, representing the minor version, gets incremented when backward-compatible functionality is added; and the Z number, representing a patch release, gets incremented when a backward-compatible bug is fixed. Such improvements can be easily underestimated, yet it’s a must-have for most modern software development scenarios where Continuous Delivery (CD) is paramount and new versions are released with great frequency.
  • TypeScript: Seasoned developers will probably already know what TypeScript is. Those who don’t won’t need to worry since we’re going to use it a lot during the Angular-related chapters of this book. For now, let’s just say that TypeScript is a Microsoft-made superset of JavaScript that allows the use of all ES2015 features (such as Default, Rest, and Spread parameters; template literals; arrow functions; Promises; and more) and adds powerful type-checking and object-oriented features during development (such as class and type declarations). The TypeScript source code can be transpiled into standard JavaScript code that all browsers can understand.
  • Server-side rendering (SSR): Angular 2 comes with Angular Universal, an open source technology that allows a back-end server to run Angular applications and serve only the resulting static HTML files to the client. In a nutshell, the server will render a first pass of the page for faster delivery to the client, and then immediately refresh it with client code. SSR has its caveats, such as requiring Node.js to be installed on the host machine to execute the necessary pre-rendering steps, as well as having the whole node_modules folder there, but can greatly increase the app’s response time for a typical internet browser, thus mitigating a known AngularJS performance issue.
  • Angular Mobile Toolkit (AMT): A set of tools specifically designed for building high-performance mobile apps.
  • Command-line interface (CLI): The new CLI introduced with Angular 2 can be used by developers to generate components, routes, services, and pipes via console/terminal commands, together with simple test shells.
  • Components: These are the main building blocks of Angular 2, entirely replacing the controllers and scopes of AngularJS, and also taking on most of the tasks previously covered by the former directives. Application data, business logic, templating, and the styling of an Angular 2 app can all be done using components.

I did my best to explore most of these features in my first book, ASP.NET Core and Angular 2, which was published in October 2016, right after the final release of the two frameworks: https://www.packtpub.com/product/asp-net-core-and-angular-2/9781786465689.

Angular 4

On March 23, 2017, Google released Angular 4: the number 3 version was skipped entirely in order to unify all the major versions of the many Angular components that had been developed separately before that date, such as Angular Router, which already was at version 3.x at the time. Starting with Angular 4, the entire Angular framework was then unified into the same MAJOR.MINOR.PATCH SemVer pattern.

The new major version brought a limited number of breaking changes, such as a new and improved routing system, TypeScript 2.1+ support (and a requirement), and some deprecated interfaces and tags. There were also a good number of improvements, including:

  • Ahead-of-time (AOT) compilation: Angular 4 compiles the templates during the build phase and generates JavaScript code accordingly. That’s a huge architectural improvement over the JIT mode used by AngularJS and Angular 2, where the app was compiled at runtime.

For example, when the application starts, not only is the app faster since the client doesn’t have to compile anything, but it throws/breaks at build time instead of during runtime for most component errors, thus leading to more secure and stable deployments.

  • Animations npm package: All the existing UI animations and effects – as well as new ones – were moved to the @angular/animations dedicated package instead of being part of @angular/core. This was a smart move to give non-animated apps the chance to drop that part of code, thereby being much smaller and arguably faster.

Other notable improvements included a new form validator to check for valid email addresses, a new paramMap interface for URL parameters in the HTTP routing module, and better internalization support.

Angular 5

Released on November 1, 2017, Angular 5 featured TypeScript 2.3 support, another small set of breaking changes, many performance and stability improvements, and a few new features, such as the following:

  • New HTTP Client API: Starting from Angular 4.3, the @angular/http module was put aside in favor of a new @angular/common/http package with better JSON support, interceptors, immutable request/response objects, and other stuff. The switch was completed in Angular 5 with the previous module being deprecated and the new one recommended for use in all apps.
  • State Transfer API: A new feature that gives the developer the ability to transfer the state of the application between the server and the client.
  • A new set of router events for more granular control over the HTTP life cycle: ActivationStart, ActivationEnd, ChildActivationStart, ChildActivationEnd, GuardsCheckStart, GuardsCheckEnd, ResolveStart, and ResolveEnd.

November 2017 was also the release month of my ASP.NET Core 2 and Angular 5 book, which covers most of the aforementioned improvements: https://www.packtpub.com/product/asp-net-core-2-and-angular-5/9781788293600.

In June 2018, that book was made available as a video course: https://www.packtpub.com/product/asp-net-core-2-and-angular-5-video/9781789531442.

Angular 6

Released in April 2018, Angular 6 was mostly a maintenance release, more focused on improving the overall consistency of the framework and its toolchain than adding new features. Therefore, there were no major breaking changes. RxJS 6 supports a new way to register providers, the new providedIn injectable decorator, improved Angular Material support (a component specifically made to implement material design in the Angular client-side UI), more CLI commands/updates, and so on.

Another improvement worth mentioning was the new CLI ng add command, which uses the package manager to download new dependencies and invoke an installation script to update our project with configuration changes, add additional dependencies, and/or scaffold package-specific initialization code.

Last, but not least, the Angular team introduced Ivy, a next-generation Angular rendering engine that aims to increase the speed and decrease the size of the application.

Angular 7

Angular 7 came out in October 2018 and was certainly a major update, as we can easily guess by reading the words written by Stephen Fluin, developer relations lead at Google and prominent Angular spokesman, on the official Angular development blog upon the official release:

”This is a major release spanning the entire platform, including the core framework, Angular Material, and the CLI with synchronized major versions. This release contains new features for our toolchain and has enabled several major partner launches.”

Here’s a list of the new features:

  • Easy upgrade: Thanks to the groundwork laid by version 6, the Angular team was able to reduce the steps that need to be done to upgrade an existing Angular app from an older version to the most recent one. The detailed procedure can be viewed by visiting https://update.angular.io, an incredibly useful Angular upgrade interactive guide that can be used to quickly recover the required steps, such as CLI commands and package updates.
  • CLI update: A new command that attempts to automatically upgrade the Angular application and its dependencies by following the procedure mentioned previously.
  • CLI prompts: The Angular CLI has been modified to prompt users when running common commands such as ng new or ng add @angular/material to help developers discover built-in features such as routing and SCSS support.
  • Angular Material and CDK: Additional UI elements such as virtual scrolling; a component that loads and unloads elements from the DOM based on the visible parts of a list, making it possible to build very fast experiences for users with very large scrollable lists; CDK-native drag-and-drop support; improved drop-down list elements; and more.
  • Partner launches: Improved compatibility with a number of third-party community projects such as Angular Console, a downloadable console for starting and running Angular projects on your local machine; AngularFire, the official Angular package for Firebase integration; Angular for NativeScript, integration between Angular and NativeScript – a framework for building native iOS and Android apps using JavaScript and/or JS-based client frameworks; some interesting new Angular-specific features for StackBlitz, an online IDE that can be used to create Angular and React projects, such as a tabbed editor and integration with the Angular Language Service; and so on.
  • Updated dependencies: Added support for TypeScript 3.1, RxJS 6.3, and Node 10, although the previous versions can still be used for backward compatibility.

The Angular Language Service is a way to get completions, errors, hints, and navigation inside Angular templates: think about it as a virtuous mix between a syntax highlighter, IntelliSense, and a real-time syntax error checker. Before Angular 7, which added the support for StackBlitz, such a feature was only available for Visual Studio Code and WebStorm.

For additional information about the Angular Language Service, take a look at the following URL: https://angular.io/guide/language-service.

Angular 8

Angular 7 was quickly followed by Angular 8, which was released on May 29, 2019. The new release is mostly about Ivy, the long-awaited new compiler/runtime of Angular: despite being an ongoing project since Angular 5, version 8 was the first one to officially offer a runtime switch to actually opt into using Ivy, which would become the default runtime starting from Angular 9.

To enable Ivy on Angular 8, the developers had to add an "enableIvy": true property to the angularCompilerOptions section within the app’s tsconfig.json file.

Those who want to know more about Ivy are encouraged to have an extensive look at the following post by Cédric Exbrayat, cofounder and trainer of the Ninja Squad website and now part of the Angular developer team: https://blog.ninja-squad.com/2019/05/07/what-is-angular-ivy/.

Other notable improvements and new features included:

  • Bazel support: Angular 8 was the first version to support Bazel, a free software tool developed and used by Google for the automation of building and testing software. It can be very useful for developers aiming to automate their delivery pipeline as it allows incremental builds and tests, and even the possibility to configure remote builds (and caches) on a build farm.
  • Routing: A new syntax was introduced to declare the lazy-loading routes using the import() syntax from TypeScript 2.4+ instead of relying on a string literal. The old syntax was kept for backward compatibility but may be dropped soon.
  • Service workers: A new registration strategy was introduced to allow developers to choose when to register their workers instead of doing it automatically at the end of the app’s start up life cycle. It’s also possible to bypass a service worker for a specific HTTP request using the new ngsw-bypass header.
  • Workspace API: A new and more convenient way to read and modify the Angular workspace configuration instead of manually modifying the angular.json file.

In client-side development, a service worker is a script that the browser runs in the background to do any kind of stuff that doesn’t require either a user interface or any user interaction. If you’re new to the concept, don’t worry – we’ll extensively talk about them in Chapter 12, Progressive Web Apps, where we’ll build our very own service worker.

The new version also introduced some notable breaking changes – mostly due to Ivy – and removed some long-time deprecated packages such as @angular/http, which was replaced by @angular/common/http in Angular 4.3 and then officially deprecated in 5.0.

A comprehensive list of all the deprecated APIs can be found in the official Angular deprecations guide at the following URL: https://angular.io/guide/deprecations.

Angular 9

Angular 9 was released in February 2020 after a long streak of release candidates through 2019 Q4 and was the most recent version for only 4 months before being replaced by its successor (Angular 10).

The new release brought the following new features:

  • JavaScript bundles and performance: An attempt to fix the very large bundle files, one of the most cumbersome issues of the previous versions of Angular, which drastically increased the download time and brought down the overall performance.
  • Ivy compiler: The new Angular build and render pipeline, shipped with Angular 8 as an opt-in preview, is now the default rendering engine.
  • Selector-less bindings: A useful feature that was available to the previous rendering engine, but missing from the Angular 8 Ivy preview, is now available to Ivy as well.
  • Internationalization: Another Ivy enhancement that makes use of the Angular CLI to generate most of the standard code necessary to create files for translators and to publish an Angular app in multiple languages, thanks to the new i18n attribute.

The new i18n attribute is a numeronym, which is often used as an alias for internationalization. The number 18 stands for the number of letters between the first i and the last n in the word internationalization. The term seems to have been coined by the Digital Equipment Corporation (DEC) around the 1970s or 1980s, together with l10n for localization, due to the excessive length of the two words.

The long-awaited Ivy compiler deserves a couple more words, being a very important feature for the future of Angular.

As the average Angular developer already knows, the rendering engine plays a major role in the overall performance of any front-end framework since it’s the tool that translates the actions and intents laid out by the presentation logic (in Angular components and templates) into the instructions that will update the DOM. If the renderer is more efficient, it will arguably require fewer instructions, thus increasing the overall performance while decreasing the amount of required JavaScript code at the same time. Since the JavaScript bundles produced by Ivy are much smaller than the previous rendering engine, Angular 9’s overall improvement is relevant in terms of both performance and size.

February 2020 was also the release month of my ASP.NET Core 3 and Angular 9 book, featuring a whole new set of source code snippets and project samples that can also be found in this book: https://www.packtpub.com/product/asp-net-core-3-and-angular-9-third-edition/9781789612165.

Angular 10

Angular 10 was released on June 24, 2020, just a few months after Angular 9. The short timeframe between Angular 9 and 10 was explained by the Angular development team as an attempt to get the framework back on its regular schedule since Angular 9 got delayed by a few weeks.

The new release was mostly focused on fixing issues: more than 700 issues were fixed and over 2,000 were touched on in the process. However, there were still quite a few important updates to be aware of:

  • Upgrade to TypeScript 3.9, as well as TSLib 2.0, and TS Lint v6. It’s worth noting that earlier versions of TypeScript are no longer supported because they are not compatible with some potentially breaking changes in the tsconfig.json file structure (see below).
  • Angular Material improvements, including a new date range picker.
  • Additional warnings when using CommonJS imports, as they can result in both larger and slower applications.
  • Optional stricter settings: Developers are now able to create new projects with a strict flag that enables stricter listing rules and bundle sizes, thereby resulting in more efficient tree-shaking (a term commonly used in JavaScript contexts for dead-code elimination using the import and export module syntax).

For additional info about the improved tsconfig.json file structure (namely, “Solution Style” tsconfig.json files), take a look at the following paragraph from the TypeScript 3.9 release notes: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html#support-for-solution-style-tsconfigjson-files.

To know more about the meaning of the term “tree-shaking,” check out the following guide: https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking.

Angular 11

Angular 11 was released on November 11, 2020, the same release day of .NET 5. The new release added the following features:

  • Component Test Harnesses, a set of classes that lets a test interact with a component via a supported API. By using the Harness API, a test insulates itself against updates to the internals of a component, such as changing its DOM structure: such an idea comes from the PageObject pattern, which is commonly used for integration testing.
  • Updated Hot Module Replacement Support: HMR is a mechanism that allows modules to be replaced without a full browser refresh; configuring HMR in Angular 11 is a lot easier, and they also introduced a new --hmr CLI command to enable it.
  • TypeScript 4.0 Support: While TypeScript 3.9 (and lower) support has been dropped, this important upgrade allows Angular 11 apps to build much faster than previous versions.
  • Webpack 5 support, although it is still experimental since the new version has only been released recently and might still not be entirely stable.
  • TSLint to ESLint migration: This is one of the most important changes to this version since TSLint and Codelyzer have been officially deprecated, and they will definitely be removed in the next release. To help developers to deal with such an update, the Angular team has introduced a three-step method that can be used to seamlessly migrate from TSLint to ESLint using the CLI.
  • Dropped support for Internet Explorer 9 and 10, as well as IE mobile.

Other new features included updated Language Service Preview, new automated migrations and schematics, some service worker improvements, lazy-loading support for named outlets, resolve guard generation via the Angular CLI, stricter types for built-in pipes, and ISO 8601 week-numbering year format support in the formatDate function.

Angular 12

Angular 12 came out on May 12, 2021, after numerous beta releases and release candidates. The major update to this version is the long-announced deprecation of the legacy View Engine compilation and rendering pipeline in favor of the now stable and objectively superior Ivy technology, thus granting faster Ahead-Of-Time compilation.

Other notable improvements include:

  • Nullish Coalescing operator (??) in Angular templates.
  • Style improvements, thanks to inline Sass support in Components (within the styles field of the @Component decorator).
  • Deprecating support for IE11, which will be removed in Angular 13.
  • HTTP improvements, such as human-readable HttpStatusCode names and some new methods for dealing with HTTP parameters and metadata more efficiently.
  • Strict mode by default. The Angular strict mode is now enabled by default in the CLI: this flag will enable several source code consistency checks in the TypeScript compiler as well as in Angular. Writing code with strict mode enabled helps developers to catch bugs early, reduce bundle size, avoid allocating unnecessary memory, follow best practices and get better IDE support, thus improving the maintainability of the app.

Angular 13

Last, but not least, we come to Angular 13, which was released on November 3, 2021, and is currently the most recent version.

The new features list includes:

  • FormControlStatus, a new type that will seamlessly include all possible status strings for form controls.
  • View Engine, which was already deprecated in Angular 12, has been removed, thus leaving the new Ivy rendering engine as the only choice. View Engine removal also means that IE11 support has been dropped as well.
  • Angular Package Format (APF) has been redesigned, removing View Engine-specific metadata, matching the format of ES2020, and adding support for Node Package Exports.
  • New Component API, which allows developers to create components with less boilerplate code.
  • Persistent Build Cache support has been enabled by default.
  • RxJS dependency version has been updated from 6.x to 7.4.
  • TestBed performance improvements that lead to faster, less memory-intensive, less interdependent, and more optimized tests.

This concludes our brief review of the recent history of the ASP.NET Core and Angular ecosystems. In the next sections, we’ll summarize the most important reasons that led us to choose them in 2021-2022.