Skip to content

Angular 18 Announced: Zoneless Change Detection and More

Angular 18 Announced: Zoneless Change Detection and More

Angular 18 Announced: Zoneless Change Detection and More

Angular 18 has officially landed, and yet again, the Angular team has proven that they are listening to the community and are committed to continuing the framework's renaissance.

The release polishes existing features, addresses common developer requests, and introduces experimental zoneless change detection. Let's examine the major updates and enhancements that Angular 18 offers.

1. Zoneless Angular

One of the most exciting features of Angular 18 is the introduction of experimental support for zoneless change detection. Historically, Zone.js has been responsible for triggering Angular's change detection. However, this approach has downsides, especially regarding performance and debugging complexity. The Angular team has been working towards making Zone.js optional, and Angular 18 marks a significant milestone in this journey.

Key Features of Zoneless Angular

  1. Hybrid Change Detection: In Angular 18, a new hybrid change detection mode is enabled by default. This mode allows Angular to listen to changes from signals and other notifications regarding changes that occur either inside an Angular zone or not. That effectively means you can write (library) code that works regardless of whether Zone.js is being used, paving the way to fully zoneless apps without compromising backward compatibility.

    For new applications, Angular enables zone coalescing by default, which removes the number of change detection cycles and improves performance. For existing applications, you can enable zone coalescing by configuring your NgZone provider in bootstrapApplication:

    bootstrapApplication(App, {
      providers: [provideZoneChangeDetection({ eventCoalescing: true })],
    });
    
  2. Experimental API for Zoneless Mode: Angular 18 introduces an experimental API to disable Zone.js entirely. This API allows developers to run applications in a fully zoneless mode, paving the way for improved performance and simpler debugging. The zoneless change detection requires an entirely new scheduler which relies on notifications from the Angular core APIs, such as ChangeDetectorRef.markForCheck (called automatically by the AsyncPipe), ComponentRef.setInput, signal updates, host listener updates, or attaching a view that was marked dirty.

  3. Improved Composability and Interoperability: Zoneless change detection enhances composability for micro-frontends and interoperability with other frameworks. It also offers faster initial render and runtime, smaller bundle sizes, more readable stack traces, and simpler debugging.

How to Try Zoneless Angular

To experiment with zoneless change detection, you can add the provideExperimentalZonelessChangeDetection provider to your application bootstrap:

bootstrapApplication(App, {
  providers: [provideExperimentalZonelessChangeDetection()],
});

After adding the provider, remove Zone.js from your polyfills in angular.json.

You can read more about the experimental zoneless change detection in the official documentation. By the way, angular.dev is now considered the official home for Angular developers!

2. Server-side Rendering and Hydration Enhancements

A feature I'm particularly excited about is the improvements to Angular's server-side rendering (SSR) and hydration in terms of developer experience and debugging:

  1. Enhanced DevTools Support: Angular DevTools now includes overlays and detailed error breakdowns to help visualize and debug hydration issues directly in the browser. This refreshing focus on developer experience shows that the Angular team wants to make the framework more approachable and user-friendly.

  2. Hydration Support for Angular Material: All Angular Material components now support client hydration and are no longer skipped, which enhances performance and user experience.

  3. Event Replay: Available in developer preview, event replay captures user interactions during SSR and replays them once the application is hydrated, ensuring a seamless user experience before complete hydration. It is powered by the same library as Google Search.

  4. i18n Hydration Support: Up to v17, Angular skipped hydration for components with i18n blocks. From v18, hydration support for i18n blocks is in developer preview, allowing developers to use client hydration in internationalized applications.

3. Stable Material Design 3

After introducing experimental support for Material Design 3 in Angular 17, Angular 18 now includes stable support.

The key features of Material Design 3 in Angular 18 include:

  1. Simplified Theme Styles: Based on CSS variables, the new theming styles offer more granular customization and a flexible API for applying color variants to components.

  2. Theming Generation Schematics: Using the Ng CLI, you can generate Material 3 themes.

  3. Sass APIs: New Sass APIs allow developers to read colors, typography, and other properties from the Material 3 theme, making it easier to create custom components.

How to use Material Design 3 in Angular 18

To use Material Design 3 in Angular 18, you can define a theme in your application's styles.scss file using the mat.defineTheme function:

@use "@angular/material" as mat;

$my-theme: mat.defineTheme(
  (
    color: (
      theme-type: light,
      primary: mat.$indigo-palette,
    ),
    typography: (
      plain-family: "Roboto",
    ),
    density: (
      scale: 1,
    ),
  )
);

Or generate a Material 3 theme using the Ng CLI:

ng generate @angular/material:m3-theme

You can then apply the theme to your application using the mat.theme mixin:

@use "@angular/material" as mat;
@use "./path/to/my-theme" as theme;

@include mat.theme($theme.$my-theme);

Head to the official guide for a more detailed guide. You'll also notice they have refreshed the docs with the new themes and further documentation.

4. Signal-Based APIs

The path to fully signal-based components includes new signal inputs, model inputs, and signal query APIs. We already wrote about them as they were in developer-preview in v17, but they have been further refined in v18. These APIs offer a type-safe, reactive way to manage state changes and interactions within components:

  1. Signal Input API: Signal inputs allow values to be bound from parent to child components. Those values are exposed using a signal and can change during the component's life cycle.

  2. Model Input API: Model inputs are a special input type that enables a component to propagate new values back to the parent component. That allows developers to keep the parent component in sync with the child component with two-way binding.

  3. Signal Query API: This was a particularly requested feature from the community. The signal query APIs work the same way as ViewChild and ContentChild under the hood, but they return signals, providing more predictable timing and type safety.

5. Fallback Content For ng-content

A very requested feature from the community, Angular 18 introduces a new ng-content directive that allows developers to define fallback content when no content is projected into a component. This feature is particularly useful for creating reusable components with default content.

Here's an example of using the new ng-content directive. Using the following component

@Component({
  selector: "app-hello",
  template: `
    <ng-content select=".greeting">Hello </ng-content>
    <ng-content>World</ng-content>
  `,
})
export class Hello {}

like this

<app-hello><span class="greeting">Howdy</span></app-hello>

will render <span class="greeting">Howdy</span> World.

6. Other Improvements

In addition to the major updates mentioned above, Angular 18 also includes several other improvements and updates:

  1. TypeScript 5.4: Angular 18 now supports TypeScript 5.4, which lets you take advantage of new features such as preserved narrowing in closures following last assignments.

  2. Global Observable in Angular Forms: Angular 18 introduces a global events observable in Angular forms, which allows you to track all changes around any abstract control and its children, including the touched or dirty in a single observable. Here's an example of how you can use the global observable:

    const control = new FormControl<string | null>(
      "initial value",
      Validators.required
    ); // use the global observable
    control.events.subscribe((value) => {
      console.log(value);
    });
    
  3. Stable Deferrable views: Deferrable views are now stable in Angular 18.

  4. Stable Control Flow: The built-in control flow is now stable in Angular 18! It is more performant than its predecessor. It also received improved type checking, including guardrails for certain performance-related anti-patterns.

  5. Route Redirects as Functions: For added flexibility in managing redirects, Angular v18 now lets you use a function for redirectTo that returns a string, which allows you to create more sophisticated redirection logic based on runtime conditions. For example:

    const routes: Routes = [
      { path: "home", component: HomeComponent },
      {
        path: "legacy-profile",
        redirectTo: ({ queryParams }) => {
          const errorService = inject(ErrorService);
          const profileId = queryParams["profileId"];
          if (profileId) {
            return `/profile/${profileId}`;
          } else {
            errorService.logError(
              new Error(
                "Navigation to profile page attempted without profile ID."
              )
            );
            return `/error`;
          }
        },
      },
      { path: "profile/:profileId", component: ProfileComponent },
    ];
    

Conclusion

Angular 18 is a significant release that brings many new features, enhancements, and experimental APIs to the Angular ecosystem. The introduction of zoneless change detection, improvements to server-side rendering and hydration, stable Material Design 3 support, signal-based APIs, and fallback content for ng-content are just a few of the highlights of this release.

The Angular team has again demonstrated its commitment to improving the framework's developer experience, performance, and flexibility. It also demonstrated a clear vision for Angular's future. If you're curious about what's next, you can check out the Angular roadmap.

This Dot is a consultancy dedicated to guiding companies through their modernization and digital transformation journeys. Specializing in replatforming, modernizing, and launching new initiatives, we stand out by taking true ownership of your engineering projects.

We love helping teams with projects that have missed their deadlines or helping keep your strategic digital initiatives on course. Check out our case studies and our clients that trust us with their engineering.

Let's innovate together!

We're ready to be your trusted technical partners in your digital innovation journey.

Whether it's modernization or custom software solutions, our team of experts can guide you through best practices and how to build scalable, performant software that lasts.

Prefer email? hi@thisdot.co