Le blog
de
Ninja Squad

What's new in Angular 22.3?

Angular 22.3.0 is here!

Angular logo

Angular 22.3 is the third minor release of the v22 cycle, with a focus on build performance, thanks to the work on the Rust-based compiler and a new library builder. It also brings router error boundaries, stricter template checks, and a few other goodies. Let's dive in!

A faster compiler in Rust

A major focus of the Angular team is the new ngp compiler, partly written in Rust, which aims to speed up builds and rebuilds.

As we were pretty curious about how it works and how much faster it is, we wrote a dedicated blog post:

👉How much faster is the new Angular compiler?

Note that some template warnings won't be available in ngp, as the new compiler does not rely on the TypeScript type checker to analyze the templates. This is a trade-off for performance, but it means some uncalled functions or signals in templates won't be caught (at least in the current version; maybe this will be improved in the future).

RIP Selectorless and signal components

The team also removed two unfinished prototypes from the codebase: signal components (signals: true) and selectorless components. Neither was available as a supported feature, so it's not a big loss, but selectorless components were looking good as you can see in our blog post, so I'm a bit sad to never get this one 😞.

Templates

strictUnknownElements

A new optional compiler flag, strictUnknownElements, has been added. It catches unknown elements that were previously silently accepted when matched by an attribute directive.

For example, consider this template:

<custom-color-picker formControlName="color" />

With ReactiveFormsModule imported, this template previously compiled even if CustomColorPicker was missing from the component’s imports.

With strictUnknownElements: true, the compiler now reports an NG8001: 'custom-color-picker' is not a known element error.

The option defaults to false in v22.3 and is planned to be enabled by default in v23.

strictNgTemplateTypes

Another optional compiler flag, strictNgTemplateTypes, detects unknown property bindings on <ng-template> elements that were previously silently ignored.

For example, a typo in ngTemplateOutlet:

<ng-template [ngTemplateOutet]="content"></ng-template>

With strictNgTemplateTypes: true, the compiler now reports an NG8002: Can't bind to 'ngTemplateOutet' since it isn't a known property of 'ng-template' error. I would have thought this was already caught, but it appears it wasn't!

The option defaults to false in v22.3, but the check is intended to become enabled by default in the next major release, as strictUnknownElements

numericCssPropertyRequiresUnit

A new extended diagnostic, numericCssPropertyRequiresUnit, is enabled by default when strictTemplates is enabled in v22.3.

It detects non-zero numeric literals, including numeric string literals, bound without a unit to supported CSS length properties:

<!-- 👇does not set the height -->
<div [style.height]="200"></div>

This template now produces the following warning by default:

NG8119: Binding a number to the CSS property 'height' will have no effect. CSS requires units for length values.
For example, use [style.height.px]="200" or [style.height]="'200px'" instead.

The check allows unitless zero and properties such as opacity that accept unitless numbers. It does not currently check values read from component properties or other non-literal expressions.

Syntax

A small addition to the template syntax: you can now use the increment (++) and decrement (--) operators in event handlers:

<button (click)="count++">Increment</button>

Both prefix and postfix forms are supported (++count, count++, --count, and count--), with the same behavior as in JavaScript.

Router

Resources

In v22.2, we introduced one of the new features of the router: router resources.

{
  path: 'races',
  component: Races,
  // 👇context contains params, queryParams, etc as signals
  resources: context => {
    const page = computed(() => context.queryParams()['page']);
    const races = httpResource<Array<RaceModel>>(() => `/api/races?page=${page()}`);
    // return a key/value object
    // - the key is the name of the data
    // - the value is the resource
    return { races };
  }
}

In v22.3, the context gains a new resources key containing a signal that exposes the ancestor routes' resources. For example, let's say you have a parent route users/:id and a child route users/:id/posts. Fetching the posts requires information from the user, the authorId for example, as showcased in our blog post explaining how to chain resources. So you want the router resource fetching the posts to depend on the router resource from the parent route. This is now possible:

{
  path: 'users/:id',
  component: Users,
  resources: context => {
    const id = computed(() => context.params()['id']);
    const user = httpResource<UserModel>(() => `/api/users/${id()}`);
    return { user };
  },
  children: [
    {
      path: 'posts',
      component: Posts,
      // 👇context now contains parent resources as a signal
      resources: context => {
        const posts = httpResource<Array<PostModel>>(({ chain }) => {
          // the resource must be read in a reactive context
          // and manually typed (default type is Resource<unknown>)
          const userResource = context.resources()['user'] as Resource<UserModel>;
          const user = chain(userResource);
          return `/api/posts?authorId=${user.authorId}`;
        });
        return { posts };
      }
    }
  ]
}

Here the user resource from the parent route is used by the child route, and the posts are only fetched when the user details are fetched. When the parent resource changes, the child resource reacts to that change and fetches the corresponding posts. Note that the parent resource must be accessed inside a resource's params function (or request callback passed to httpResource), otherwise it might not be available, and Angular throws:

NG04020: Router resources should be accessed inside a resource's 'params' (e.g. 'resource({ params: ({chain}) => chain(ctx.resources()["name"]) })').

With withComponentInputBinding(), the parent resource can also be bound to a component input, just like the route's own resources:

export class Posts {
  // 👇this was already possible
  readonly posts = input.required<Array<PostModel>>();
  // 👇this is new
  readonly user = input.required<UserModel>();
}

Error fallback component

Another addition of v22.2 was the boundaries feature. The feature is still in developer preview but the router can now leverage it as well.

A new withErrorBoundaries() function is available to configure the router (in developer preview as well), enabling boundaries for routes. This feature allows us to display a fallback component when a route fails because the component threw an error during creation or rendering, including when reading the value of a failed resource. This does not handle navigation errors like errors from guards, resolvers, or blocking route resources. This component can be globally configured in withErrorBoundaries():

provideRouter(
  routes,
  withComponentInputBinding(),
  withErrorBoundaries({
    // 👇 Default fallback component for routes
    defaultErrorComponent: RouteErrorFallback,

    // 👇Also allows to define an action to do when an error arises
    onError: (error, details) => {
      // Call a logger API for example
    }
  })
);

Or the component can be configured/overridden for a route, using a new key errorComponent:

{
  path: 'users/:id',
  component: User,
  // 👇
  errorComponent: UserErrorFallback
},

When you navigate to /users/12, if User throws an error during creation or rendering, then the router instantiates UserErrorFallback inside the <router-outlet> instead.

The fallback components can access the error and the other parameters via input bindings:

@Component({
  selector: 'ns-user-error-fallback',
  template: `
    <h1>Ohoh! Failed to load user #{{ id() }}</h1>
    <p>{{ error()?.message }}</p>
  `
})
export class UserErrorFallback {
  readonly error = input<Error>();
  readonly id = input<string>();
}

Unlike the @boundary feature in templates, there is no explicit "reset" API yet.

If you try to use errorComponent in a route without the withErrorBoundaries() configuration, the router logs a warning in the browser console:

The route 'users/:id' defines an 'errorComponent', but router error boundaries are not enabled. Add 'withErrorBoundaries()' to 'provideRouter' for it to take effect.

View transitions are stable

Angular v17 introduced withViewTransitions() as an experiment to enable view transitions in an application.

By default, you get a nice fade-in/fade-out transition between views when navigating from one route to another. You can customize the animation using CSS, animate the whole view or skip part of it, or indicate which DOM elements are in fact the same entities in the old and new views: the browser will then do its best to animate between the states.

This feature is now stable, as all major browsers support it!

I really like this feature. If you want to see what this can achieve, try navigating from our book catalogue to a book page: the cover and title move into their new positions! We also use view transitions when opening an article from our blog.

Scroll and Navigation API

When scroll restoration is enabled with withInMemoryScrolling({ scrollPositionRestoration: 'enabled' }) (or 'top'), the router normally scrolls to the top after a forward navigation, even one that only changes a query parameter.

You can opt out of scrolling for a navigation by setting scroll to 'manual' in its NavigationBehaviorOptions. This was already possible programmatically, and is now also possible via an input of the RouterLink directive in v22.3:

<a routerLink="/users" [queryParams]="{ sort: 'asc' }" scroll="manual">Sort</a>

This is useful for tabs or filters further down the page: the URL changes, but the router leaves the scroll position alone. The default behavior, 'after-transition', follows the router's scrolling configuration.

The new input also works when the router uses the browser Navigation API via withExperimentalPlatformNavigation (which is, you get it, still experimental).

Focus control

Speaking of the experimental browser Navigation API support: when the router uses it, the browser resets focus after each navigation. This can be painful if you have a simple search form, as the user will lose focus in the input if they enable a filter that triggers a navigation to set a query parameter.

To avoid that, a new option has been added to NavigationBehaviorOptions: focusReset. Like the scroll option, it can be set to:

  • 'after-transition' (the default), the browser moves focus to the first element with the autofocus attribute, or to the <body>
  • 'manual', the browser doesn't reset focus.

Unlike the scroll option, this option only applies when using withExperimentalPlatformNavigation, and is itself experimental.

Navigation in tests

The RouterTestingHarness gained a new navigate() method, in addition to its existing navigateByUrl(). This mirrors what can be done with the router, where you can use both. navigate() allows you to specify NavigationExtras (including options that aren't in the URL, like state, skipLocationChange, or replaceUrl). You previously had to inject the router and use its navigate method to do so.

Defer

@defer now allows you to define a scroll margin when using the viewport trigger (in addition to rootMargin and threshold). scrollMargin is a fairly specific option of the IntersectionObserver API. Unlike rootMargin, scrollMargin expands the clipping bounds of nested scroll containers. This allows deferred content to be loaded or prefetched before it enters the visible area of a nested scroller.

AI

The WebMCP API introduced as an experiment in v22 has allowed you to define annotations in a tool declaration since v22.2. In v22.3, a new annotation is supported: debugging. It indicates if the tool is intended for debugging and development purposes rather than end-user agent interaction. Signal forms exposed as tools via experimentalWebMcpTool are automatically configured with debugging: false.

HTTP

Have you ever had to change an API from GET to POST because you needed to pass too many parameters and were limited by the length of a GET request URL?

Well, the HTTP spec introduced a new method, called QUERY, defined in RFC 10008. QUERY allows safe, idempotent queries with a request body.

HttpClient now supports the HTTP QUERY method via http.query(url, body, options) in v22.3. Your server must support this HTTP method of course.

http.query<Array<UserModel>>('/api/users/search', {
  roles: ['admin', 'editor'],
  active: true
});

QUERY requests are also eligible for Angular's SSR transfer cache by default, alongside GET and HEAD requests.

CLI

New library builder

Most of the work done in this CLI release is about a new library builder, replacing ng-packagr, called @angular/build:library. ng-packagr is a standalone project, while the new builder is in the CLI project, and shares lots of code with the other builders.

The new architecture of this builder should bring better performance, mostly to incremental rebuilds when updating TS or SCSS files in the lib and for libraries that are using multiple entry points. Some quick benchmarks show roughly 2–4× faster incremental rebuilds.

Newly generated libraries now use this builder by default. The CLI also provides a new ng generate entry-point testing --project=my-lib schematic to generate a secondary entry point, allowing consumers to import its APIs from my-lib/testing. This schematic is only available for libraries using the new builder.

The CLI team provided an optional migration that you can run, to migrate from ng-packagr to @angular/build:library. The migration is optional, but the older @angular/build:ng-packagr builder is now deprecated and logs a warning recommending the new builder:

ng update @angular/cli --migrate-only --name=use-library-builder

I migrated the two small OSS libraries that we maintain (ngx-valdemort and ngx-speculoos): the migration was super simple! No real performance gains that I could spot, to be honest, though 🤷. As the libraries are quite small, I suppose we don't really see the benefits of the new build pipeline.

Tests

Small addition: the unit-test builder now allows you to set the polyfills option. The polyfills were previously always inherited from the buildTarget, and can now be overridden.

The --test-runner option is now deprecated when generating applications and libraries. Selecting Karma is still possible for now, but newly generated projects will only be configured with Vitest in a future version.

SSR

It is now possible to pre-render routes as <name>.html instead of <name>/index.html. This feature is inspired by Astro, SvelteKit, Hugo and others and can be enabled via prerender.format, which you set to 'file' (instead of the current default 'directory'). This is useful if you use static hosting that serves /foo.html for /foo, as it avoids a redirect, but not if you produce a server (the option is then ignored as @angular/ssr expects the directory layout).

Formatting

I'm happy to present this new feature as I'm the one who introduced it 😉: the CLI can now use your oxfmt config to format files generated via ng generate! It only supported Prettier until now: a CLI project created via ng new is nowadays generated with a Prettier config and dependency out of the box. We don't have (yet) the possibility to create a project with oxfmt directly, but oxfmt now lets you configure Angular template formatting regardless of the filename as the remaining blocking issue has been closed recently. So you can remove Prettier and add oxfmt, and the CLI now checks both and picks the formatter found, preferring Prettier when both are installed, to format the generated component, service, pipe, etc.

Summary

That's all for this release. Stay tuned!

All our materials (ebook, online training and training) are up to date with these changes if you want to learn more!

How much faster is the new Angular compiler?

The Angular team recently announced that they were working on a new version of the compiler, called ngp, partly written in Rust.

They recently landed the bulk of this new compiler in a massive commit adding more than 370k lines, including around 56k lines of Rust. As I usually read all commits line by line, this one took me a long time 😅. But I dived in to get an idea of how much faster it is and, more importantly, how it works.

This blog post is an explanation of the compiler architecture, and a naive benchmark to check out what it's got!

Architecture of ngc

ngc is the version of the compiler we already know. When Angular was first released in 2016, this mechanism of pre-compiling templates to JS functions with TypeScript type-checking was very innovative.

10 years later, this has been adopted in some way or another by all other frameworks. And, while type-safety in templates is awesome, the performance of this Angular compiler has always been a bit sub-par compared to the other ecosystems, especially on large projects, where it can take several minutes for a full cold build.

This partly comes down to how ngc is architected. Its very first version was a wrapper around tsc, the TypeScript compiler. Then, in version 4.3, the Angular team leveraged the Transformer API introduced in TS v2.3. Transformers rewrite the compiler’s representation of code before that code is emitted.

The compiler then evolved further with Ivy. Its initial Type Check Block (TCB) implementation landed in Angular 7's experimental Ivy compiler, before Ivy became the default in Angular 9. TCBs represent template expressions as TypeScript code for type-checking, separately from the runtime definitions and template instructions generated for the application.

ngc compilation pipeline

To speed things up, a lot of our tools have taken the path of being rewritten from JS/TS in languages that compile to native binaries: TypeScript v7 is a rewrite in Go, Rolldown is a rewrite of Rollup in Rust, etc. The issue is that the Go version of tsc does not offer the same Transformer API (yet?), and even if it does at some point, the cost of crossing the JS/Go boundary would be too high.

So the idea of the Angular team is two-fold:

  • decouple Angular compilation from the TS Transformer API and separate type-checking from code emission
  • write this new tool in Rust

Architecture of ngp

The new compiler is called ngp. ngp separates Angular code generation from TypeScript type-checking. Unlike the default ngc command, it doesn’t itself run the TypeScript checker or emit JavaScript: it produces TypeScript that downstream tools can check and build.

It is a hybrid tool: it's written in Rust, but still uses the existing template compiler written in TypeScript. So there are 3 steps:

  • Rust analysis, using oxc, VoidZero's low-level toolchain to parse/modify JS/TS code in Rust. This step discovers Angular declarations, reads the decorators and metadata, and resolves their relationships.
  • TypeScript code generation, reusing the existing @angular/compiler for template compilation. This step compiles templates and generates runtime code and type-check blocks (TCBs) in 2 different output files.
  • downstream processing: a TypeScript compiler checks the application and TCBs, while TypeScript or a bundler processes the runtime code into JavaScript.

ngp compilation pipeline

As the analysis is done in Rust, it is much faster than its TS counterpart (it runs in parallel and streams compilation tasks), and consumes less memory.

TS code generation still uses the existing compiler, so no speed improvement here. We can imagine that this will change in the future, with a Rust version of this compiler as well (announced in the blog post from the team). The downstream processing is also a place where we'll gain time: it is no longer necessary to use TS v6, and TS v7 (the Go version) can be used to type-check. And TS v7 is several times faster than v6! In addition, a few alternative implementations of TS v7 have also appeared that could be even faster. More on that later.

The generation of JS code can be done in parallel by TS or by another tool, like esbuild (written in Go as well), whose specialty is to strip TypeScript syntax from the code to generate JS code, without type-checking (which is of course way faster).

The three phases in practice

Let's take a simple component with a signal and an inline template:

@Component({
  selector: 'app-user',
  template: '<p>Hello {{ name() }}</p>'
})
export class User {
  readonly name = signal('Cédric');
}

1. Rust analysis

The Rust analyzer extracts the component's metadata and sends it to the TypeScript backend:

{
  "className": "User",
  "component": {
    "selector": "app-user",
    "template": "<p>Hello {{ name() }}</p>",
    "standalone": true
  }
}

The template is still a string: Rust has not compiled it or generated a TCB.

2. TypeScript code generation

The TypeScript backend uses the existing Angular template compiler to produce two files. The first, user.ts, contains the runtime code, including this template function:

function User_Template(rf: number, ctx: any): any {
  if (rf & 1) {
    i0.ɵɵdomElementStart(0, 'p');
    i0.ɵɵtext(1);
    i0.ɵɵdomElementEnd();
  }
  if (rf & 2) {
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1('Hello ', ctx.name());
  }
}

The first branch creates the elements; the second updates the text using the signal's value.

The second file, user.ngtypecheck.ts, contains the TCB:

function _tcb1(this: i0.User) {
  if (true) {
    '' + this.name();
  }
}

Notice that the runtime template function uses ctx: any, whereas the TCB has a typed this: i0.User. This lets TypeScript detect missing properties or invalid calls in the template.

3. Downstream processing

For this example, tsgo --noEmit checked both files without errors, while esbuild independently emitted JavaScript, without bundling or minification. The template function keeps its rendering instructions but loses its TypeScript annotations:

function User_Template(rf, ctx) {
  if (rf & 1) {
    i0.ɵɵdomElementStart(0, 'p');
    i0.ɵɵtext(1);
    i0.ɵɵdomElementEnd();
  }
  if (rf & 2) {
    i0.ɵɵadvance();
    i0.ɵɵtextInterpolate1('Hello ', ctx.name());
  }
}

The TCB is only used for checking, not shipped as runtime code. And esbuild does not check types: that remains TypeScript's job.

At the time of writing this, ngp is still an internal tool that the team is actively working on to bring up to par with the existing ngc pipeline. The same test suite is run for both, and some tests are still failing for the new compiler. We can also imagine that some optimizations will be done later, but let's take a first look at the build times!

A naive benchmark

Note: This has been measured with a beta version of ngp (22.3.0-next.2) on a "CI-like" machine. The same benchmark on macOS shows faster times, but similar gains.

I built the native version of the ngp compiler, then ran it on 3 projects:

  • a small one with 15 components
  • a medium one with 56 components
  • and a large one with 1714 components

I used esbuild or Rolldown for per-file JavaScript emission, without bundling or minification. For type-checking, I used TypeScript v7.1 (beta at the time of writing, but faster than v7.0), and also tried tsrs, a port of the TS compiler in Rust by Max Schwenk and the Cloudflare/VoidZero team, which is even faster (but of course a bit experimental for now).

Compilation, type-checking and JavaScript emission timings for three project sizes, comparing ngc with ngp plus tsgo and esbuild, and ngp plus tsrs and rolldown

As you can see, we have nearly a 2-3x speedup already across all project sizes! Memory usage is also way down: on the largest project it goes from 2.8Go to only 1.4Go. ngp takes the bulk of the time, with the hatched area showing the estimated contribution of the existing template compiler. Downstream tools are then quite fast, with tsrs and Rolldown being faster than tsgo and esbuild.

Summary

This is already very promising, and there are certainly further gains to be made when the team focuses on performance optimization. We should also see a rewrite of the template compiler in the future, which will improve the times for the second phase. For the downstream part, we don't know yet which tools the Angular CLI team will use. The safe choice is TS itself of course, but it's interesting to see alternatives like tsrs that have popped up and offer further performance improvements!

All the times in the benchmark are cold builds. During development or tests, the incremental compilation should get the same order of magnitude of gains. It means that what sometimes takes 5-10 seconds to refresh on large projects should only take 2-3 seconds.

Can't wait to use this in our daily work!