Angular 16: Rethinking Reactivity and Improving Performance
Table of Contents

Angular 16: Rethinking Reactivity and Improving Performance

Introduction

The Angular team has recently unveiled Angular 16, ushering in a new era of performance and developer experience improvements. Among the most notable features of this release is the introduction of a new reactivity model for Angular, which not only enhances runtime performance but also simplifies the mental model for reactivity. This makes it easier to understand the flow of data through your application and the dependencies of your views.

One of the best aspects of Angular 16 is its backward compatibility and interoperability with the current system, which ensures a smooth transition for developers looking to upgrade their existing projects. In this blog post, we will explore the key features and enhancements that Angular 16 has to offer, including the Angular Signals library, server-side rendering and hydration improvements, standalone APIs and migration, the developer preview of the esbuild-based build system, and much more.

Join us as we dive into the world of Angular 16 and uncover how these new features can significantly improve your application's performance and overall developer experience.

Angular Signals

One of the major highlights of Angular 16 is the introduction of Signals. This new library allows developers to define reactive values and express dependencies between them, thereby improving the performance of the application without introducing large mental overhead. By doing so, the Angular Signals library brings about several benefits, including:

   1. Better runtime performance by reducing the number of computations during change detection.

   2. A simpler mental model for reactivity, making it clear what the dependencies of the view are and how data flows through the app.

   3. Fine-grained reactivity, which in future releases will enable checking for changes only in affected components.

To get started with the Angular Signals library, you'll find a new signals library as part of @angular/core and an RxJS interop package - @angular/core/rxjs-interop. Here's a simple example of how to use Angular Signals within a component:


import { Component, signal, computed, effect } from '@angular/core'; 

  

@Component({ 

  selector: 'my-app', 

  standalone: true, 

  template: ` 

    {{ fullName() }} <button (click)="setName('John')">Click</button> 

  `, 

}) 

export class App { 

  firstName = signal('Jane'); 

  lastName = signal('Doe'); 

  fullName = computed(() => `${this.firstName()} ${this.lastName()}`); 

  

  constructor() { 

    effect(() => console.log('Name changed:', this.fullName())); 

  } 

  

  setName(newName: string) { 

   this.firstName.set(newName); 

  } 

} 

In the example above, we create a computed value fullName, which depends on the signals firstName and lastName. We also declare an effect, which callback will execute every time we change the value of any of the signals it reads — in this case fullName, which means it transitively also depends on firstName and lastName.

Enhanced Server-Side Rendering and Hydration

Server-side rendering (SSR) is a key aspect of building modern Angular applications, and it has been identified as one of the top opportunities for improvement according to the annual developer survey. To address this, Angular 16 introduces significant enhancements to SSR and hydration in collaboration with the Chrome Aurora team.

The developer preview of full app non-destructive hydration brings several benefits, including:

   1. No content flickering on a page for end users.

   2. Improved Web Core Vitals in certain scenarios.

   3. Easy integration with existing apps using just a few lines of code.

   4. Incremental adoption of hydration with the ngSkipHydration attribute in templates for components performing manual DOM manipulation.

In early tests, full app non-destructive hydration has shown up to a 45% improvement in Largest Contentful Paint. To get started with this feature, simply add a few lines to your main.ts file:

import { 
  bootstrapApplication, 
  provideClientHydration, 
} from '@angular/platform-browser'; 


bootstrapApplication(RootCmp, { 
  providers: [provideClientHydration()] 
}); 

Resumability and Partial Hydration

One paragraph from the Angular team made us believe that resumability and partial hydration are coming to Angular.  

We’re very partial to all of these changes and we certainly plan to resume this direction of where Angular is going with server side rendering, and there’s a lot more ahead with v17 and beyond. Stay tuned.

What do these concepts mean?  

Resumability

Resumability is about pausing the execution of an application on the server and resuming it on the client without having to replay and download all the application logic. This makes the application startup instantaneous and significantly improves the performance.  

Partial Hydration

Partial hydration is an advanced technique that allows individual pieces of a server-rendered application to be “booted up” over time, rather than initializing the entire application at once. This enhances the performance by reducing the client-side footprint of mostly static parts of the application. The Angular team will address the challenges and compromises associated with partial hydration, such as caching issues and client-side navigation, to provide a more efficient and optimized framework.  

Why Does the Angular Team Focus So Much on Performance?

The Angular team focuses heavily on their framework's performance due to the direct correlation between improved performance and increased user engagement, conversions, and revenue for businesses. Faster loading times result in better user experience and, subsequently, higher conversion rates. Here are some examples of the impact of improved performance (source):

1. Every 100ms faster results in 1% more conversions: Mobify found that a 100ms decrease in homepage load speed led to a 1.11% increase in session-based conversion, yielding an average annual revenue increase of ~$380,000.

2. 50% faster load times lead to 12% more sales: AutoAnything experienced a 12% to 13% boost in sales when they reduced page load time by half.

3. 20% faster load times result in 10% more conversions: Furniture Village, after auditing their site speed and implementing improvements, saw a 20% reduction in page load time and a 10% increase in conversion rate.

4. 40% faster perceived wait times lead to 15% more sign-ups: Pinterest managed to reduce perceived wait times by 40%, which increased search engine traffic and sign-ups by 15%.

5. 850ms faster load times result in 7% more conversions: COOK reduced its average page load time by 850 milliseconds, which increased conversions by 7%, decreased bounce rates by 7%, and increased pages per session by 10%.

6. 1 second of slowness leads to 10% fewer users: The BBC found that they lost an additional 10% of users for every additional second their site took to load.

These statistics highlight the importance of performance optimization in web frameworks like Angular. By focusing on performance improvements, the Angular team ensures that developers can build fast and efficient applications, leading to higher user satisfaction, increased conversions, and more successful online businesses. Perhaps, if the framework is fast enough, it may become a general purpose framework, such as React or Vue.

Standalone APIs and Migration

Angular is known for its robustness and suitability for mission-critical applications, which is why the Angular team is cautious when introducing major changes. Standalone APIs were first explored years ago, and in 2022, they were released under a developer preview. After more than a year of collecting feedback and iterating on the APIs, Angular 16 encourages even wider adoption of standalone APIs.

To help developers transition their apps to standalone APIs, the Angular team has developed migration schematics and a standalone migration guide. To initiate the migration process in your project directory, simply run:

ng generate @angular/core:standalone

This command will convert your code, remove unnecessary NgModule classes, and update the project's bootstrap to use standalone APIs.

Standalone ng new Collection

With Angular 16, you can now create new projects as standalone from the start. To try the developer preview of the standalone schematics, ensure you have Angular CLI v16 installed and run:

ng new --standalone

This command will generate a simpler project output without any NgModules. Additionally, all the generators in the project will produce standalone directives, components, and pipes.

Developer Preview: esbuild-based Build System

Over a year ago, the Angular team announced their work on experimental support for esbuild in the Angular CLI to expedite build processes. With Angular 16, the esbuild-based build system enters developer preview, and early tests have shown over a 72% improvement in cold production builds.

In ng serve, Vite is now utilized as the development server, while esbuild powers both development and production builds. It's important to note that Angular CLI relies on Vite exclusively as a development server, as the Angular compiler requires a different compilation model than Vite to support selector matching and maintain a dependency graph between components.

Better Unit Testing with Jest and Web Test Runner

Based on developer surveys in both the Angular and broader JavaScript communities, Jest has emerged as one of the most popular testing frameworks and test runners. In response to numerous requests for Jest support, Angular 16 introduces experimental support for Jest, significantly reducing complexity as real browsers are not required.

In a future release, existing Karma projects will be migrated to Web Test Runner to continue supporting browser-based unit testing, a change that will be a no-op for the majority of developers.

Testing changes are always important to big teams at large corporations, where code that they ship must be thoroughly tested.

Language Service Improvements: Auto-Import Components and Pipes

Developers often encounter errors from the CLI or language service when using a component or pipe in a template without importing the corresponding implementation. To address this issue and improve the overall developer experience, Angular 16 introduces a new language service feature that allows auto-importing components and pipes.

This enhancement seamlessly integrates with signal-based components, making it easier for developers to work with their applications without worrying about missing imports.

Signal-Based Component Inputs

Angular 16 also brings a new approach to component inputs with the introduction of the input function, which replaces the @Input decorator as the means of declaring a component input. Signal-based inputs provide several advantages, such as improved reactivity and the ability to work with model inputs for two-way binding.

Here's an example of declaring some signal-based inputs:

import { Component, input } from '@angular/core'; 

  

@Component({ 

  signals: true, 

  selector: 'user-profile', 

  template: ` 

    <p>Name: {{ firstName() }} {{ lastName() }}</p> 

    <p>Account suspended: {{ suspended() }}</p> 

  `, 

}) 

export class UserProfile { 

  firstName = input<string>(); // Signal<string|undefined> 

  lastName = input('Smith'); // Signal<string> 

  suspended = input<boolean>(false, { 

    alias: 'disabled', 

  }); // Signal<boolean> 

} 

In this example, the input function accepts two parameters: an initial value (similar to signal) and an options object. The input function returns a read-only Signal, and reading the value from an input always provides the up-to-date bound value. It's important to note that signal-based inputs are indistinguishable from non-signal inputs to component consumers, using the same binding syntax.

Conclusion

Angular 16 brings a plethora of exciting new features and improvements, including a new reactivity model, the Angular Signals, server-side rendering and hydration enhancements, standalone APIs and migration, an esbuild-based build system, and much more. These advancements not only improve application performance but also significantly enhance the overall developer experience.

We encourage developers to explore Angular 16 and take advantage of its powerful features and optimizations. As the Angular team continues to innovate and refine the framework, we eagerly anticipate future releases that will further advance the development landscape.

The new version of the enterprise web development framework brings many improvements, with many more coming in future version. Enterprise web apps will benefit greatly.

Liked the article? subscribe to updates!
360° IT Check is a weekly publication where we bring you the latest and greatest in the world of tech. We cover topics like emerging technologies & frameworks, news about innovative startups, and other topics which affect the world of tech directly or indirectly.

Like what you’re reading? Make sure to subscribe to our weekly newsletter!
Relevant Expertise:
No items found.
Share

Subscribe for periodic tech i

By filling in the above fields and clicking “Subscribe”, you agree to the processing by ITMAGINATION of your personal data contained in the above form for the purposes of sending you messages in the form of newsletter subscription, in accordance with our Privacy Policy.
Thank you! Your submission has been received!
We will send you at most one email per week with our latest tech news and insights.

In the meantime, feel free to explore this page or our Resources page for eBooks, technical guides, GitHub Demos, and more!
Oops! Something went wrong while submitting the form.

Related articles

Our Partners & Certifications
© 2024 ITMAGINATION, A Virtusa Company. All Rights Reserved.