DEV Community

Jarosław Żołnowski
Jarosław Żołnowski

Posted on

What's New in Angular v19?

Angular v19 is here, and it’s packed with powerful features and enhancements to make building high-performance web apps even easier. With this release, developers can look forward to improvements that enhance developer experience, boost app performance, and simplify APIs to make development faster and more efficient. Let’s explore what Angular v19 brings to the table.


Keeping Things in Sync with linkedSignal

One of the standout features in Angular v19 is the introduction of linkedSignals. This new reactive primitive ensures multiple signals stay in sync, making it perfect for maintaining derived states that depend on other signals.

Here's a quick example: say you have a list of users and want to keep the selected user highlighted even when the list changes. With linkedSignal, you can write code that automatically adjusts the selection behind the scenes, keeping things clean and organized.

import { linkedSignal, signal } from '@angular/core';

export class UserSelectionComponent {
  protected readonly availableUsers = signal<{ id: number; name: string }[]>([
    { id: 1, name: 'User1' },
    { id: 2, name: 'User2' },
    { id: 3, name: 'User3' },
  ]);

  protected selectedUserId = linkedSignal({
    source: this.availableUsers,
    computation: (users, previous) => {
      if (previous?.value && users.some(user => user.id === previous.value)) {
        return previous.value;
      }
      return null;
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

In this example, linkedSignal recalculates the selected user ID whenever the list of available users changes, reducing complexity in state management.


Streamlined Data Fetching with the resource API

Fetching data just got easier with the new resource API. It simplifies async data handling by combining loaders, request tracking, and reactivity. This means less code for you and cleaner components that focus on what matters.

Here’s how you can use resource to fetch and manage user profile data:

import { resource, signal } from '@angular/core';

const userId = signal('user_1');

protected userDetails = resource({
  request: this.userId,
  loader: async ({ request: userId, abortSignal }) => {
    const response = await fetch(`https://api.example.com/users/${userId}`, { signal: abortSignal });
    return await response.json() as UserDetails;
  },
});

userDetails.value; // Access user details
userDetails.isLoading; // Check loading state
userDetails.error; // Handle errors

protected updateUser(name: string): void {
  this.userDetails.update((user) => (user ? { ...user, name } : undefined));
}

protected reloadProfile(): void {
  this.userDetails.reload();
}
Enter fullscreen mode Exit fullscreen mode

Think of it like having a personal data assistant. You tell it what data you need, and it handles the whole process, letting you know when it's loading, if there are any errors, and of course, providing the data itself.


Faster Rendering with Incremental Hydration

Incremental Hydration is a game-changer for server-side rendered (SSR) applications. Instead of hydrating the entire app at once, Angular now hydrates UI sections only when needed, reducing the initial JavaScript payload and processing time.

To enable this, you just need to tweak your app's configuration a bit:

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

export const appConfig: ApplicationConfig = {
  providers: [
    provideClientHydration(withIncrementalHydration()),
  ],
};
Enter fullscreen mode Exit fullscreen mode

Now you can control exactly which parts get hydrated using hydration triggers with the @defer directive:

@defer (hydrate on hover) {
  <app-hydrated-content></app-hydrated-content>
}
Enter fullscreen mode Exit fullscreen mode

In this case, the component will only load when hovered. This enables fine-grained hydration of components, ensuring better performance and resource usage.


Flexible Render Modes with ServerRoute

Ever wanted to choose how different parts of your app render? Angular v19 introduces ServerRoute interface, giving you the power to decide whether a route should be rendered on the server, pre-rendered in the background, or handled by the client.

For example, you might want your login page to be server-side rendered for security reasons, while your dashboard could be client-side rendered for a more interactive experience:

export const serverRouteConfig: ServerRoute[] = [
  { path: '/login', mode: RenderMode.Server },
  { path: '/dashboard', mode: RenderMode.Client },
  { path: '/**', mode: RenderMode.Prerender },
];
Enter fullscreen mode Exit fullscreen mode

One cool thing about ServerRoute is that it lets you dynamically resolve route parameters during pre-rendering. This means you can use your Angular services to fetch data and customize the content before it's even sent to the browser.

import { ServerRoute } from '@angular/platform-server';
import { inject } from '@angular/core';

export const serverRoutes: ServerRoute = [
  {
    path: '/users/:id',
    mode: 'prerender',
    async getPrerenderPaths() {
      const userService = inject(UserService);
      const userIds = await userService.getUserIds();
      return userIds.map(id => ({ id }));
    },
  },
];
Enter fullscreen mode Exit fullscreen mode

The getPrerenderPaths function executes in an injection context, allowing to use Angular services to fetch and resolve user id dynamically.


Instant Feedback with Enhanced HMR

Angular v19 takes Hot Module Replacement (HMR) to the next level. Before, if you tweaked some CSS or changed your template, the whole app would have to rebuild and refresh in the browser. It worked, sure, but this process often interrupted the developer’s flow and reset the application state, like if you were filling out a form and suddenly...everything's gone.. With the enhanced HMR in Angular v19, these interruptions are a thing of the past.

Now, those annoying interruptions are history! With the new and improved HMR in v19, when you change your component's styles or template and hit save, Angular is smart enough to just compile the parts you changed. It then sends those updates to the browser and patches the running app without a full page refresh. This means you see your changes instantly.

Imagine you're working on a product page and need to tweak the style of a button while maintaining the current application state. With HMR, we can change the button’s styles:

.button-primary {
  background-color: #007bff; // Updated color 
}
Enter fullscreen mode Exit fullscreen mode

And...see changes instantly without a full page reload or losing form input, scroll position, or other dynamic states.

The best part? Hot module replacement for styles is enabled by default in v19, so you get it right out of the box.


Enhanced Security with Automatic Content Security Policy

Security is a big deal, and Angular v19 is making it easier to keep your apps safe with a new feature called AutoCSP. This is currently in developer preview, so it's still being refined, but it's a really cool step forward. AutoCSP automatically generates a hash-based Content Security Policy (CSP).

Basically, a CSP acts as a security layer, specifying which resources a browser is allowed to load and execute. Each script in your app gets a unique "fingerprint" (a unique hash). The browser will only run a script if its fingerprint is on the CSP's "approved" list. This is a super effective way to stop attackers from injecting malicious scripts because they can't create the correct fingerprint for their sneaky code.

To enable the AutoCSP feature, we need to update the angular.json configuration file:

{
  "projects": {
    "my-angular-app": {
      "architect": {
        "build": {
          "options": {
            "security": {
              "autoCSP": true
            }
          }
        }
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Once you've done this, Angular takes care of the rest. During the build process, it automatically generates the CSP with the correct fingerprints for all your inline scripts in index.html.


Standalone Components as the Default

Angular v19 makes a big push towards simpler components. Remember those NgModules? Well, in many cases, you won't need them anymore! Standalone components are now the default way to create components. And for those who want to fully embrace the standalone way, there's a strict mode you can enable in your tsconfig.json file:

{
  "angularCompilerOptions": {
    "strictStandalone": true
  }
}
Enter fullscreen mode Exit fullscreen mode

This ensures everything in your app is using the modern standalone approach, leading to a cleaner and more consistent project structure and lets you take full advantage of the latest Angular features.


Improved Theming with Angular Material

With the release of Angular v19, the Angular Material and CDK teams have taken a significant step forward by improving the theming API. It's now way easier to create and customize themes, building on the already awesome Material 3 framework. The new API not only streamlines theming but also provides developers with tools to make component-specific customizations more efficient and expressive. Say goodbye to repetitive code and hello to streamlined theming:

Making Themes Easier with mat.theme

In the past, creating a custom theme in Material required defining themes for each component separately. It worked, but it was often a lot of repetitive code. Now, with v19, there's a new mat.theme mixin that lets you define your entire theme – colors, fonts, spacing – in one place.

In earlier versions of Angular Material, creating a custom theme required defining themes for individual components using separate mixins. This approach, while powerful, often led to repetitive and verbose code. Angular v19 introduces the mat.theme mixin, which allows developers to define custom themes using a single, unified declaration.

Here’s an example:

@use '@angular/material' as mat;

@include mat.theme(
  $color-palette,
  $typography-config,
  $density-config
);
Enter fullscreen mode Exit fullscreen mode

This single line of code sets up your entire theme - the definition of color palettes, typography, and density. The resulting theme is applied globally, reducing boilerplate and making theme management easier.

More Ways to Customize Material 3

Angular Material v19 also gives you more flexibility with colors and fonts. You can now create multiple themes for different parts of your app and even switch between them on the fly:

@use '@angular/material' as mat;

$dark-theme: mat.define-theme((
  color: (
    primary: mat.$cyan-palette,
    secondary: mat.$amber-palette,
    theme-type: dark
  ),
  typography: mat.define-typography((font-family: 'Georgia, serif')),
  density: 1
));

body.dark-mode {
  @include mat.theme($dark-theme);
}
Enter fullscreen mode Exit fullscreen mode

Component-Specific Overrides

One of the coolest additions (at least from my perspective) is the ability to make targeted customizations for individual components using the new overrides API. This allows developers to tweak specific design tokens for components without altering the global theme.

Let's say you want to change the background and divider color of a mat-sidenav component:

@include mat.sidenav-overrides((
  'content-background-color': lightblue,
  'container-divider-color': darkgray,
));
Enter fullscreen mode Exit fullscreen mode

This lets you tweak specific components while still keeping a consistent overall look and feel.

Enhanced Drag & Drop with Mixed Orientation

Angular's CDK now supports drag-and-drop in two dimensions, making it even more powerful for building interactive user interfaces. This opens the door for creating things like Kanban boards, grid layouts, or even creative layout editors, without the need for third-party libraries.

Support for Tab Reordering

Angular v19 introduces support for tab reordering, enabling users to rearrange tabs dynamically. This feature enhances the user experience for applications with complex tab-based interfaces.

New Time Picker Component

Another addition is the brand new Time Picker Component, which simplifies time selection in forms and input fields. The component is highly customizable, integrates seamlessly with Angular forms, and supports various formats.


Wrapping It Up

Angular v19 is a big step forward, giving developers powerful tools to build apps faster and more secured. From reactive features to security improvements and simplified standalone defaults, Angular v19 is a release worth checking out. With support for advanced theming, dynamic prerendering, and productivity-enhancing tools like HMR, Angular continues to set the standard for front-end frameworks. So go ahead and start exploring the possibilities!

Top comments (0)