What's new in Angular 18.1?

Angular 18.1.0 is here!

Angular logo

This is a minor release with some nice features: let’s dive in!

TypeScript 5.5 support

Angular v18.1 now supports TypeScript 5.5. This means that you can use the latest version of TypeScript in your Angular applications. You can check out the TypeScript 5.5 release notes to learn more about the new features: it’s packed with new things! For example, it’s no longer necessary to manually define type guards when filtering arrays, with the new inferred type predicate feature.

@let syntax

The main feature of this release is undoubtedly the new @let syntax in Angular templates. This new syntax (in developer preview) allows you to define a template variable in the template itself, without having to declare it in the component class.

The syntax is @let name = expression;, where name is the name of the variable (and can be any valid JavaScript variable name) and expression is the value of the variable. Let’s say our component has a count field defined in its class, then we can define a variable in the template like this:

@let countPlustwo = count + 2;
<p>{{ countPlustwo }}</p>

If the count value changes, then the countPlustwo value will be updated automatically. This also works with the async pipe (and the other ones, of course):

@let user = user$ | async;
@if (user) {
  <p>{{ user.name }}</p>
}

Note that you can’t declare several variables (with @let or #) with the same name in the same template:

NG8017: Cannot declare @let called 'value' as there is another symbol in the template with the same name.

You also can’t use a variable before its declaration:

NG8016: Cannot read @let declaration 'user' before it has been defined.

which prevents to use it like @let user = user() in case you thought about unwrapping a signal value into a variable of the same name.

This new feature can be handy when you want to use a value in several places in your template, especially if it is a complex expression. Sometimes you can create a dedicated field in the component class, but sometimes you can’t, for example in a for loop:

@for(user of users; track user.id) {
  <div class="name">{{ user.lastName }} {{ user.firstName }}</div>
  <div class="address">
    <span>{{ user.shippingAddress.default.number }}&nbsp;</span>
    <span>{{ user.shippingAddress.default.street }}&nbsp;</span>
    <span>{{ user.shippingAddress.default.zipcode }}&nbsp;</span>
    <span>{{ user.shippingAddress.default.city }}</span>
  </div>
}

This can be written more cleanly using @let 🚀:

@for(user of users; track user.id) {
  <div class="name">{{ user.lastName }} {{ user.firstName }}</div>
  <div class="address">
    @let address = user.shippingAddress.default;
    <span>{{ address.number }}&nbsp;</span>
    <span>{{ address.street }}&nbsp;</span>
    <span>{{ address.zipcode }}&nbsp;</span>
    <span>{{ address.city }}</span>
  </div>
}

afterRender/afterNextRender APIs

Angular v16.2 introduced two new APIs to run code after the rendering of a component: afterRender and afterNextRender. You can read more about them in our Angular 16.2 blog post.

In Angular v18.1, these APIs have been changed (they are still marked as experimental) to no longer need a phase parameter, which was introduced in Angular v17, as we explained in our Angular 17 blog post.

The phase parameter is now deprecated: we now pass to these functions an object instead of a callback, to specify the phases you want to use. You can still use the callback form with no phase, which is equivalent to using the MixedReadWrite mode. There are 4 phases available in the new object form: earlyRead, mixedReadWrite, read, and write. If you only need to read something, you can use the read phase. If you need to write something that affects the layout, you need to use write. For example, to initialize a chart in your template:

export class ChartComponent {
  @ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>;

  constructor() {
    afterNextRender({
      write: () => {
        const ctx = this.canvas.nativeElement;
        new Chart(ctx, { type: 'line', data: { ... } });
      }
    });
  }
}

If your write callback depends on something you need to read first, you must use earlyRead to get the information you need before the write phase, and Angular will call the write callback with the value returned by the earlyRead callback:

afterRender({
  earlyRead: () => nativeEl.getBoundingClientRect(),
  //👇 The `rect` parameter is the value returned by the `earlyRead` callback
  write: (rect) => {
    otherNativeEl.style.width = rect.width + "px";
  },
});

This exists to avoid intermixing reads and writes if possible, and thus make things faster by avoiding “layout trashing”. We previously had to call afterRender twice, once for the read and once for the write phase, but now we can do it in a single call, which is more efficient and cleaner.

The phase option still exists but is now deprecated. Even if these APIs are an experimental feature, the Angular team provided a migration schematics to update your code to the new syntax 😍.

toSignal equality function

As you may know, if you read our blog post about signals, a Signal can define its own equality function (it uses Object.is by default).

In Angular v18.1, the toSignal function now also accepts an equal parameter to specify the equality function to use in the signal it creates.

The RouterLink directive now accepts an UrlTree as input. This allows you to pass a pre-constructed UrlTree to the RouterLink directive, which can be useful in some cases.

Until now, we could pass either a string or an array to the RouterLink directive. For example, we could write:

<a [routerLink]="['/users', user.id]">User {{ user.name }}</a>

Now we can also use an UrlTree:

export class HomeComponent {
  userPath = inject(Router).createUrlTree(["/users", user.id]);
}

and in the template:

<a [routerLink]="userPath">User {{ user.name }}</a>

Note that when doing so, you can’t define the queryParams, fragment, queryParamsHandling and relativeTo inputs of the RouterLink directive in the template. You have to define them in the UrlTree itself, or you’ll see the following error:

Error: NG04016: Cannot configure queryParams or fragment when using a UrlTree as the routerLink input value.

Router browserUrl

The NavigationBehaviorOptions object, used for the options of the navigate/navigateByUrl of the Router service or the RedirectCommand object introduced in Angular v18 now accepts a browserUrl option. This option allows you to specify the URL that will be displayed in the browser’s address bar when the navigation is done, even if the matched URL is different. This does not affect the internal router state (the url of the Router will still be the matched one) but only the browser’s address bar.

const canActivate: CanActivateFn = () => {
  const userService = inject(UserService);
  const router = inject(Router);
  if (!userService.isLoggedIn()) {
    const targetOfCurrentNavigation = router.getCurrentNavigation()?.finalUrl;
    const redirect = router.parseUrl("/401");
    // Redirect to /401 internally but display the original URL in the browser's address bar
    return new RedirectCommand(redirect, {
      browserUrl: targetOfCurrentNavigation,
    });
  }
  return true;
};

Extended diagnostic for uncalled functions

A new extended diagnostic has been added to warn about uncalled functions in event bindings:

So for example:

<button (click)="addUser">Add user</button>

yields the following error (if you have strictTemplates enabled):

NG8111: Functions must be invoked in event bindings: addUser()

Angular CLI

faster builds with isolatedModules

TypeScript has an option called isolatedModules that warns you if you write code that can’t be understood by other tools by just looking at a single file.

If you enable this option on your project, you should hopefully have no warnings, and you can get a nice boost in build performances, as CLI v18.1 will delegate the transpilation of your TS files into JS files to esbuild instead of the TypeScript compiler 🚀

On a rather large application, ng build went from 49s to 32s, just by adding isolatedModules: true in my tsconfig.json file 🤯.

isolatedModules will be enabled by default in the new projects generated by the CLI.

WASM support

The CLI now supports the usage of Web Assembly… in zoneless applications! The application can’t use ZoneJS as the CLI needs to use native async/await to load WASM code and ZoneJS prevents that.

Anyway this can be interesting for some people, and you can write code like:

import { hash } from "./hash.wasm";

console.log(hash(myFile));

inspect option

We can note the addition of a --inspect option for ng serve/ng dev, only possible for SSR/SSG applications. This flag starts a debug process, by default on port 9229, allowing to attach a debugger to go through the code executed on the server. You can use Chrome Inspect, VS Code, or your favorite IDE to attach to the process (see the NodeJS docs). You can then add breakpoints into your code, and the debugger will stop when this code is executed on the server when you load the corresponding page in your browser. You can specify a different host or port if needed with ng serve --inspect localhost:9999 for example.

chunk optimizer

If you want to reduce the number of chunk files, an experimental optimization has been added to the build step. You may have noticed that since we shifted from webpack to esbuild as the underlying build tool, the number of generated chunks has increased quite a bit. This is because there is no real optimization done on chunks. So we sometimes end up with really small chunks when running ng build. Some build tools have options to specify a minimal size, but esbuild doesn’t. That’s why the CLI team is experimenting with an additional rollup pass to optimize the generated chunks and try to merge some of them or add some directly into the main bundle when it makes sense.

On one of our largest applications, it reduces by half the number of chunks, and the initial page now only needs to load 3 JS files instead of… 118 😲. It does add a bit of build time though.

To try this on your own application, you can run:

NG_BUILD_OPTIMIZE_CHUNKS=1 ng build

This is still experimental for now but will probably be enabled automatically in a future version, based on the initial file entry count and size.

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!


What's new in Angular 18.0?

Angular 18.0.0 is here!

Angular logo

This is a major release with some nice features: let’s dive in!

Control flow syntax is now stable!

The control flow syntax introduced in Angular 17 is no longer a developer preview feature and can safely be used. As it is now the recommended way to write templates, you should consider using it in your applications. You can easily migrate your applications using the provided schematics.

👉 To learn more, check out our dedicated blog post.

Since we wrote this blog post, two warnings have been added to catch potential issues in your templates with for loops.

As you know the track option is now mandatory in @for loops. A new warning has been added in development mode to warn you if you have duplicated keys used by the track option:

WARN: 'NG0955: The provided track expression resulted in duplicated keys for a given collection.
Adjust the tracking expression such that it uniquely identifies all the items in the collection.
Duplicated keys were:
key "duplicated-key" at index "0" and "1".'

This is a warning that you can see in the browser console or when running unit tests. It typically happens if you pick a property that is not unique in your collection.

Another warning has been added to catch potential issues with the tracking expression. If the tracking expression leads to the destruction and recreation of the complete collection, a warning will be displayed:

WARN: 'NG0956: The configured tracking expression (track by identity)
caused re-creation of the entire collection of size 20.
This is an expensive operation requiring destruction and subsequent creation of DOM nodes, directives, components etc.
Please review the "track expression" and make sure that it uniquely identifies items in a collection.'

This typically happens if you use the track item option and if you recreate all the collection items when there is a change. Note that the warning only applies if the repeated element is considered “expensive” to create, but the bar is currently set quite low (a text node with a binding is already considered expensive).

Defer syntax is stable

The @defer syntax is also stable. @defer lets you define a block of template that will be loaded lazily when a condition is met (with all the components, pipes, directives, and libraries used in this block lazily loaded as well).

👉 We wrote a detailed blog post about this feature if you want to learn more about it.

Signal standardization proposal

This is not an Angular v18 news, but as you may have heard, some of the most popular framework authors (included the Angular and Vue team for example) have been working on a proposal to standardize signals in the JavaScript language.

The proposal is at the first stage, so it might take a long time, probably at least several years, or even never happened.

You can deep dive into the proposal or into this interesting blog post to learn more about it.

TL;DR: new Signal.State() would be the equivalent of signal() in Angular. new Signal.Computed() would be the equivalent of computed(). There are no equivalents for effect: as all frameworks have slightly different needs, this is left out of the scope of the proposal, and frameworks can implement it as they see fit based on new Signal.subtle.Watcher().

Fun fact: the current Signal polyfill in the proposal is based on the Angular implementation!

Zoneless change detection

Angular v18 introduces a new way to trigger change detection. Instead of relying on ZoneJS to know when something has possibly changed, the framework can now schedule a change detection by itself.

To do so, a new scheduler has been added to the framework (called ChangeDetectionScheduler), and this scheduler is internally used to trigger change detection. This new scheduler is enabled by default in v18, even if you use ZoneJS. However, the goal is to progressively move away from ZoneJS and rely only on this new scheduler.

With this new scheduler, the framework no longer only relies on ZoneJS to trigger change detection. Indeed, the new scheduler triggers a change detection when a host or template listener is triggered, when a view is attached or removed, when an async pipe detects a new emission, when the markForCheck() method is called, when you set a signal value, etc. It does so by calling ApplicationRef.tick() internally.

Opting out of the new scheduler

The new scheduler is enabled by default in v18. This means that Angular gets notified of potential changes by ZoneJS (as it used to) and by the new scheduler (when a signal is set, an async pipe receives a new value, etc.). The framework then runs the change detection. This should not impact your application, as Angular will only run the change detection once even if notified by several sources. But if you want to opt out of the new scheduler, you can use the provideZoneChangeDetection() function with ignoreChangesOutsideZone set to true:

bootstrapApplication(AppComponent, {
  providers: [
    // this restores the behavior of Angular before v18
    // and ignores the new scheduler notifications
    provideZoneChangeDetection({ ignoreChangesOutsideZone: true })
  ]
});

Experimental zoneless change detection

But you can also try to only rely on this new scheduler, and no longer on ZoneJS, to trigger change detection. This is an experimental feature, and you can enable it by using the provider function provideExperimentalZonelessChangeDetection() in your application.

bootstrapApplication(AppComponent, {
  providers: [
    // 👇
    provideExperimentalZonelessChangeDetection()
  ]
});

When doing so, the framework will no longer rely on ZoneJS to trigger change detection. So you can remove ZoneJS from your application if you want to (and if you have no dependencies that rely on it, of course). In that case, you can remove zone.js from the polyfills in your angular.json file.

It should work out of the box if all your components are OnPush and/or rely on signals! 🚀

I tried it on a small application fully written with signals and it worked like a charm. Of course, this is not something we will be able to do in all applications, but it’s a nice step forward towards a zoneless Angular. In particular, if you use a component library that isn’t ready for zoneless support, you’ll have to wait until it is. If you want to prepare your application for this new feature, you can start by progressively moving your components to OnPush.

Testing

Note that the provideExperimentalZonelessChangeDetection function can also be used in tests, so you can test your application without ZoneJS, and make sure your components are correctly working with this new feature.

You can currently add the provider in each test, or globally to all your tests by adding it in the TestBed configuration, in the test.ts file of your application (this file is no longer generated in new projects, but you can add it back manually):

@NgModule({
  providers: [provideExperimentalZonelessChangeDetection()]
})
export class ZonelessTestModule {}

getTestBed().initTestEnvironment(
  [BrowserDynamicTestingModule, ZonelessTestModule],
  platformBrowserDynamicTesting()
);

Then, instead of relying on fixture.detectChanges() that triggers the change detection, you can simply use await fixture.whenStable() and let Angular trigger the change detection (as it would when running the application). This is because the ComponentFixture used by the framework in zoneless mode uses the “auto detect changes” strategy by default.

So, similarly to using OnPush in your components to prepare for the zoneless future, a good way to prepare your tests is to progressively replace detectChanges() with await fixture.whenStable() and enable “auto-detect changes” in your tests.

This is something that has been existing for quite some time in Angular. If you want to use it in your current tests, even without using provideExperimentalZonelessChangeDetection, you can either call fixture.autoDetectChanges() at the beginning of your test, or add the following provider to your test configuration:

providers: [
  { provide: ComponentFixtureAutoDetect, useValue: true }
]

We’re probably going to update our ebook and the tests we provide in our online training to use this strategy.

Note that some testing features that use ZoneJS are not supported with provideExperimentalZonelessChangeDetection(), like fakeAsync and tick(). If you need to fake time in your tests, you can use the jasmine.clock APIs instead.

Debugging existing applications

If you want to check if your current application is ready for zoneless change detection, you can use provideExperimentalCheckNoChangesForDebug():

bootstrapApplication(AppComponent, {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }), // or provideExperimentalZonelessChangeDetection()
    provideExperimentalCheckNoChangesForDebug({
      interval: 1000, // run change detection every second
      useNgZoneOnStable: true, // run it when the NgZone is stable as well
      exhaustive: true // check all components
    })
  ]
});

This will run a change detection every second and check if any component has been changed without triggering a change detection. If such a change is detected, a NG0100: ExpressionChangedAfterItHasBeenCheckedError error will be thrown in the console. This should allow you to track down the components that need to be updated to work with zoneless change detection.

Zone.js status

ZoneJS is still a dependency of Angular and will be for a while. It is now officially in maintenance mode, and will not ship new features, but will still be maintained for bug fixes and security issues.

Fallback for ng-content

<ng-content> is a powerful feature in Angular, but it has a cumbersome limitation: it can’t have fallback content. This is no longer the case in Angular v18!

We can now add some content inside the <ng-content> tag, and this content will be displayed if no content is projected in the component.

For example, let’s consider a CardComponent with a title and a content that can be projected:

<div class="card">
  <div class="card-body">
    <h4 class="card-title">
      <!-- 👇 If the title is not provided, we display a default title -->
      <ng-content select=".title">Default title</ng-content>
    </h4>
    <p class="card-text">
      <ng-content select=".content"></ng-content>
    </p>
  </div>
</div>

Now, if we use this component without providing a title, the default title will be displayed!

Forms events

The AbstractControl class (the base class for form controls, groups, arrays, and records) now has a new property called events.

This field is an observable that emits events when the control’s value, status, pristine state, or touched state changes. It also emits when the form is reset or submitted.

For example, let’s consider a form group for a user with a login and a password:

fb = inject(NonNullableFormBuilder);
userForm = this.fb.group({
  login: ['', Validators.required],
  password: ['', Validators.required]
});

  constructor() {
    this.userForm.events.subscribe(event => {
      if (event instanceof TouchedChangeEvent) {
        console.log('Touched: ', event.touched);
      } else if (event instanceof PristineChangeEvent) {
        console.log('Pristine: ', event.pristine);
      } else if (event instanceof StatusChangeEvent) {
        console.log('Status: ', event.status);
      } else if (event instanceof ValueChangeEvent) {
        console.log('Value: ', event.value);
      } else if (event instanceof FormResetEvent) {
        console.log('Form reset');
      } else if (event instanceof FormSubmitEvent) {
        console.log('Form submit');
      }
    });
  }

As you can see, several types of events can be emitted: TouchedChangeEvent, PristineChangeEvent, StatusChangeEvent, ValueChangeEvent, FormResetEvent and FormSubmitEvent.

If I enter a first character in the login field, the console will display:

Pristine: false
Value: Object { login: "c", password: "" }
Status: INVALID
Touched: true

All events also have a source property that contains the control that emitted the event (here the login control). The source contains the form itself for form reset and submission events.

Router and redirects

The redirectTo property of a route now accepts a function instead of just a string. Previously, we were only able to redirect our users to a static route or a route with the same parameters. The RedirectFunction introduced in v18 allows us to access part of the ActivatedRouteSnapshot to build the redirect URL. I say “part of” because the activated route is not fully resolved when the function is called. For example, the resolvers haven’t run yet, the child routes aren’t matched, etc. But we do have access to the parent route params or the query params for example, which was not previously possible. This function is also similar to guards, and is run in the environment injector: this means you can inject services if needed. The function can return a string or a UrlTree.

provideRouter([
  // ...
  {
    path: 'legacy-users',
    redirectTo: (redirectData) => {
      const userService = inject(UserService);
      const router = inject(Router);
      // You also have access to 'routeConfig', 'url', 'params', 'fragment',  'data',  'outlet', and 'title'
      const queryParams = redirectData.queryParams;
      // if the user is logged in, keep the query params
      if (userService.isLoggedIn()) {
        const urlTree = router.parseUrl('/users');
        urlTree.queryParams = queryParams;
        return urlTree;
      }
      return '/users';
    }
  }
])

A similar improvement has been made in guards. The GuardResult type returned by a guard has been augmented from boolean | UrlTree to boolean | UrlTree | RedirectCommand. A guard could already return an UrlTree to redirect the user to another route, but now it can also return a RedirectCommand to redirect the user to another route with a specific navigation behavior, as a RedirectCommand is an object with two properties: redirectTo (the UrlTree to navigate to) and navigationBehaviorOptions (the navigation behavior to use):

provideRouter([
  // ...
  {
    path: 'users',
    component: UsersComponent,
    canActivate: [
      () => {
        const userService = inject(UserService);
        return userService.isLoggedIn() || new RedirectCommand(router.parseUrl('/login'), {
          state: { requestedUrl: 'users' } 
        });
      }
    ],
  }
])

Resolvers can now also return a RedirectCommand. The first resolver to do so will trigger a redirect and cancel the current navigation.

withNavigationErrorHandler() has also been updated to be able to return a RedirectCommand.

HttpClientModule deprecation

Now that the ecosystem is moving towards standalone components, we’re starting to see the deprecation of the first Angular modules. Starting with v18, HttpClientModule (and HttpClientTestingModule, HttpClientXsrfModule, and HttpClientJsonpModule) are deprecated.

As you probably know, you can now use provideHttpClient() (with options for XSRF or JSONP support) and provideHttpClientTesting() as a replacement.

But, as usual, the Angular team provides a schematic to help you migrate your application. When running ng update @angular/core, you’ll be prompted to migrate your HTTP modules if you still have some in your application.

Internationalization

The utility functions offered by @angular/common to work with locale data have been deprecated in favor of the Intl API. It is no longer recommended to use getLocaleCurrencyCode(), getLocaleDateFormat(), getLocaleFirstDayOfWeek(), etc. Instead, you should use the Intl API directly, for example Intl.DateTimeFormat to work with locale dates.

Server-Side Rendering

We have two new features in Angular v18 that are related to Server-Side Rendering (SSR).

SSR and replay events

It is now possible to record user interactions during the hydration phase, and replay them when the application is fully loaded. As you may know, the hydration phase is the phase where the server-rendered HTML is transformed into a fully functional Angular application, where listeners are added to the existing elements.

But during this phase, the user can interact with the application, and these interactions are lost (if the hydration process is not fast enough).

So for some applications, it can be interesting to record these interactions and replay them when the application is fully loaded.

This used to be done via a project called preboot in Angular, but this project was no longer maintained. Instead of reviving preboot, the Angular team decided to implement this feature directly in the framework. But they did not start from scratch: in fact, they used something that already existed inside Google, in the Wiz framework. Wiz is not open-source, but it is widely by Google for their applications (Google Search, Google Photos, etc.). You can read about the ambitions of the Wiz and Angular teams to “merge” the two frameworks in this blog post on angular.io. Wiz started to use the signals API from Angular (that’s why Youtube is now using Signals), and now Angular is using the replay events feature from Wiz. That’s why these two features are in a packages/core/primitives directory in the Angular codebase: they are part of Angular but are shared by the two frameworks.

To enable this feature, you can use the withEventReplay() (developer preview) function in your server-side rendering configuration:

providers: [
  provideClientHydration(withEventReplay())
]

When doing so, Angular will add a JS script at the top of your HTML page, whose job is to replay events that happened during the hydration phase. To do so, it adds a listener at the root of the document, and listens to a set of events that can happen on the page using event delegation. It does know which events it needs to listen to, as Angular collected them when rendering the page on the server. So for example, if you render a page that contains elements which have a (click) or a (dblclick) handler, Angular will add listeners for these events:

<script>window.__jsaction_bootstrap('ngContracts', document.body, "ng", ["click","dblclick"]);</script>

When the application is loaded and stable, the script then replays the events that happened during the hydration phase, thus triggering the same actions as the user did. Quite a nice feature, even if it is probably useful only for some applications.

SSR and Internationalization

The Angular SSR support is improving with each version. One year ago, Angular v16 introduced progressive hydration, as we explained in this blog post. There was one missing feature at the time: the internationalization support. Angular would skip the elements marked with i18n during SSR. This is now solved in v18! If your application uses the builtin i18n support of the framework, you can now use SSR. The support is in developer preview, and can be enabled with withI18nSupport().

Angular CLI

The CLI has also been released in version v18, with some notable features.

Performance improvements

The CLI now builds projects with a larger number of components faster. The commit mentions some really nice gains but I was not able to reproduce them in my experiments on large projects.

ng dev

The ng serve command is now aliased to ng dev (in addition to the existing ng s). This aligns with the Vite ecosystem, where the development server is usually started using npm run dev.

Speaking of commands, the ng doc command has been removed from the CLI in v18.

New build package

The Angular CLI now has a new package for building applications: @angular/build. It contains the esbuild/Vite builders, that were previously in the @angular-devkit/build-angular package. This allows the new package to only have Vite and ESBuild as dependencies, and not Webpack. The serve/build/extract-i18n builders are now in this new package. The @angular-devkit/build-angular package can still be used, as it provides an alias to the now-moved builders.

You’ll notice that an optional migration can be run when updating your application to v18, to update your angular.json file to use the new package (where @angular-devkit/build-angular is replaced by @angular/build) and update your package.json accordingly (to add @angular/build and remove @angular-devkit/build-angular).

This will only be done if you don’t use any Webpack-based builders in your applications, so the migration does nothing if you have tests using Karma for example (as they run using Webpack).

Less and PostCSS dependencies

The CLI supports Sass, Less, and PostCSS out of the box, and until now, these dependencies were installed in your node_modules when creating a new application (even if you were not using these dependencies).

Less and PostCSS are now optional dependencies for the new @angular/build package and need to be installed explicitly if you switch to the new package.

When you update your application to v18, these dependencies will be added automatically by ng update if you choose to switch to @angular/build (and if you’re using them of course).

Native async/await in zoneless applications

ZoneJS has a particularity: it can’t work with async/await. So you may not know it, but every time you use async/await in your application, your code is transformed by the CLI to use “regular” promises. This is called downleveling, as it transforms ES2017 code (async/await) into ES2015 code (regular promises).

As we are now able to build applications without ZoneJS (even if it is still experimental), the CLI doesn’t downlevel async/await when zone.js is not in the application polyfills. This should make the build a tiny bit faster and lighter in that case.

New project skeleton updates

If you want to upgrade to v18 without pain (or to any other version, by the way), I have created a Github project to help: angular-cli-diff. Choose the version you’re currently using (17.3.0 for example), and the target version (18.0.0 for example), and it gives you a diff of all files created by the CLI: angular-cli-diff/compare/17.3.0…18.0.0. It can be a great help along with the official ng update @angular/core @angular/cli command.

You’ll notice that the assets folder has been replaced by a public folder in new projects. You’ll also note that the app.config.ts file now contains the provideZoneChangeDetection() provider by default with the eventCoalescing option set to true (which avoids the change detection being triggered several times by ZoneJS when an event bubbles and is listened to by several template listeners).

Summary

That’s all for this release. v19 will probably be dedicated to stabilizing the signals APIs introduced these past months. We should also see a new feature to declare variables in the template itself, using @let, as well as an option to switch to Intl-based internationalization. Stay tuned!

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


What's new in Angular 17.3?

Angular 17.3.0 is here!

Angular logo

This is a minor release with some nice features: let’s dive in!

TypeScript 5.4 support

Angular v17.3 now supports TypeScript 5.4. This means that you can use the latest version of TypeScript in your Angular applications. You can check out the TypeScript 5.4 release notes to learn more about the new features.

New template compiler

Angular now uses a new template compiler! The work on this compiler started more than a year ago and has been done in parallel with the other features we saw in the previous releases to eventually pass all of the existing tests. It’s now the case, and this new compiler is now the default in Angular 17.3.

This compiler is based on an intermediate representation of template operations, a common concept in compilers, for example in LLVM. This IR semantically encodes what needs to happen at runtime to render and change-detect the template. Using an IR allows for different concerns of template compilation to be processed independently, which was not the case with the previous implementation. This new compiler is easier to maintain and extend, so it is a great foundation for future improvements in the framework.

Note that the compiler emits the same code as the previous one, so you should not see any difference in the generated code.

output functions

A new (developer preview) feature was added to allow the declaration of outputs similarly to the input() function.

As for inputs, you can use the output() function to define an output:

ponySelected = output<PonyModel>();
// ^? OutputEmitterRef<PonyModel>

The output() function returns an OutputEmitterRef<T> that can be used to emit values. OutputEmitterRef is an Angular class, really similar to a simplified EventEmitter but that does not rely on RxJS (to limit the coupling of Angular with RxJS).

The function accepts a parameter to specify options, the only one available for now is alias to alias the output.

As with EventEmitter, you can use the emit() method to emit a value:

ponySelected = output<PonyModel>();
// ^? OutputEmitterRef<PonyModel>
select() {
  this.ponySelected.emit(this.ponyModel());
}

You can also declare an output without a generic type, and the OutputEmitterRef will be of type OutputEmitterRef<void>. You can then call emit() without a parameter on such an output.

OutputEmitterRef also exposes a subscribe method to manually subscribe to the output. This is not something you’ll do often, but it can be handy in some cases. If you manually subscribe to an output, you’ll have to manually unsubscribe as well. To do so, the subscribe method returns an OutputRefSubscription object with an unsubscribe method.

Two new functions have been added to the rxjs-interop package to convert an output to an observable, and an observable to an output.

Angular always had the capability of using observables other than EventEmitter for outputs. This is not something that is largely used, but it’s possible. The new outputFromObservable function allows you to convert an observable to an output:

ponyRunning$ = new BehaviorSubject(false);
ponyRunning = outputFromObservable(this.ponyRunning$);
// ^? OutputRef<boolean>

The outputFromObservable function returns an OutputRef<T>, and not an OutputEmitterRef<T>, as you can’t emit values on an output created from an observable. The output emits every event that is emitted by the observable.

startRunning() {
  this.ponyRunning$.next(true);
}

It is also possible to convert an output to an observable using the outputToObservable function if needed. You can then use .pipe() and all the RxJS operators on the converted output.

These interoperability functions will probably be rarely used. output(), on the other hand, will become the recommended way to declare outputs in Angular components.

HostAttributeToken

Angular has always allowed to inject the value of an attribute of the host element. For example, to get the type of an input, you can use:

@Directive({ 
  selector: 'input',
  standalone: true
})
class InputAttrDirective {
  constructor(@Attribute('type') private type: string) {
    // type would be 'text' if `<input type="text" />
  }
}

Since Angular v14, injection can be done via the inject() function as well, but there was no option to get an attribute value with it.

This is now possible by using a special class HostAttributeToken:

type = inject(new HostAttributeToken('type'));

Note that inject throws if the attribute is not found (unless you pass a second argument { optional: true }).

RouterTestingModule deprecation

The RouterTestingModule is now deprecated. It is now recommended to provideRouter() in the TestBed configuration instead.

New router types

The router now has new types to model the result of guards and resolvers.

For example, the CanActivate guard was declared like this:

export type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree;

This is because the guard can return a boolean to allow or forbid the navigation, or an UrlTree to trigger a redirection to another route. This result can be synchronous or asynchronous.

The signature has been updated to:

export type CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => MaybeAsync<GuardResult>;

GuardResult is a new type equal to boolean | UrlTree, and MaybeAsync<T> is a new generic type equal to T | Observable<T> | Promise<T>.

A resolver function now also returns a MaybeAsync<T>. You can keep using the older signatures but the new ones are more concise.

Angular CLI

Angular CLI v17.3 doesn’t bring a lot of new features, but we can note that deployUrl is now supported in the application builder. It was initially marked as deprecated but was re-introduced after community feedback.

Summary

That’s all for this release. The next stop is v18, where we should see some developer preview features becoming stable. Stay tuned!

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


What's new in Angular 17.2?

Angular 17.2.0 is here!

Angular logo

This is a minor release with some nice features: let’s dive in!

Queries as signals

A new developer preview feature has been added to allow the use of queries as signals. viewChild(), viewChildren(), contentChild(), and contentChildren() functions have been added in @angular/core and return signals.

Let’s go through a few examples.

You can use viewChild to query the template:

// <canvas #chart></canvas>
canvas = viewChild<ElementRef<HTMLCanvasElement>>('chart');
// ^? Signal<ElementRef<HTMLCanvasElement> | undefined>

// <form></form> with FormsModule
form = viewChild(NgForm);
// ^? Signal<NgForm | undefined>

As you can see, the return type is a Signal containing the queried ElementRef<HTMLElement> or undefined, or the queried component/directive or undefined.

You can specify that the queried element is required to get rid of undefined:

canvas = viewChild.required<ElementRef<HTMLCanvasElement>>('chart');
// ^? Signal<ElementRef<HTMLCanvasElement>>

If the element is not found, you’ll have a runtime error:

'NG0951: Child query result is required but no value is available.
Find more at https://angular.io/errors/NG0951'

This error can also happen if you try to access the query result too soon, for example in the constructor of the component. You can access the query result in the ngAfterViewInit/ngAfterViewChecked lifecycle hooks, or in the afterNextRender/afterRender functions.

You can also use viewChildren to query multiple elements. In that case, you get a Signal containing a readonly array of elements, or an empty array if no element is found (we no longer need QueryList \o/): chart.component.ts

canvases = viewChildren<ElementRef<HTMLCanvasElement>>('chart');
// ^? Signal<ReadonlyArray<ElementRef<HTMLCanvasElement>>>

The functions accept the same option as @ViewChild and @ViewChildren, so you can specify the read option to query a directive or provider on an element.

As you can imagine, the same is possible for contentChild and contentChildren.

For example, if we want to build a TabsComponent that can be used like this:

<ns-tabs>
  <ns-tab title="Races" />
  <ns-tab title="About" />
</ns-tabs>

We can build a TabDirective to represent a tab:

@Directive({
  selector: 'ns-tab',
  standalone: true
})
export class TabDirective {
  title = input.required<string>();
}

then build the TabsComponent with contentChildren to query the directives:

@Component({
  selector: 'ns-tabs',
  template: `
    <ul class="nav nav-tabs">
      @for (tab of tabs(); track tab) {
        <li class="nav-item">
          <a class="nav-link">{{ tab.title() }}</a>
        </li>
      }
    </ul>
  `,
  standalone: true
})
export class TabsComponent {
  tabs = contentChildren(TabDirective);
  // ^? Signal<ReadonlyArray<TabDirective>>
}

As for the @ViewChild/@ViewChildren decorators, we can specify the descendants option to query the tab directives that are not direct children of TabsComponent:

tabs = contentChildren(TabDirective, { descendants: true });
// ^? Signal<ReadonlyArray<TabDirective>>
<ns-tabs>
  <div>
    <ns-tab title="Races" />
  </div>
  <ns-tabgroup>
    <ns-tab title="About" />
  </ns-tabgroup>
</ns-tabs>

As viewChild, contentChild can be required.

model signal

Signals also allow a fresh take on existing patterns. As you probably know, Angular allows a “banana in a box” syntax for two-way binding. This is mostly used with ngModel to bind a form control to a component property:

<input name="login" [(ngModel)]="user.login" />

Under the hood, this is because the ngModel directive has a ngModel input and a ngModelChange output.

So the banana in a box syntax is just syntactic sugar for the following:

<input name="login" [ngModel]="user.login" (ngModelChange)="user.login = $event" />

The syntax is, in fact, general and can be used with any component or directive that has an input named something and an output named somethingChange.

You can leverage this in your own components and directives, for example, to build a pagination component:

@Input({ required: true }) collectionSize!: number;
@Input({ required: true }) pageSize!: number;

@Input({ required: true }) page!: number;
@Output() pageChange = new EventEmitter<number>();

pages: Array<number> = [];

ngOnChanges(): void {
  this.pages = this.computePages();
}

goToPage(page: number) {
  this.pageChange.emit(page);
}

private computePages() {
  return Array.from({ length: Math.ceil(this.collectionSize / this.pageSize) }, (_, i) => i + 1);
}

The component receives the collection, the page size, and the current page as inputs, and emits the new page when the user clicks on a button.

Every time an input changes, the component recomputes the buttons to display. The template uses a for loop to display the buttons:

@for (pageNumber of pages; track pageNumber) {
  <button [class.active]="page === pageNumber" (click)="goToPage(pageNumber)">
    {{ pageNumber }}
  </button>
}

The component can then be used like:

<ns-pagination [(page)]="page" [collectionSize]="collectionSize" [pageSize]="pageSize"></ns-pagination>

Note that page can be a number or a signal of a number, the framework will handle it correctly.

The pagination component can be rewritten using signals, and the brand new model() function:

collectionSize = input.required<number>();
pageSize = input.required<number>();
pages = computed(() => this.computePages());

page = model.required<number>();
// ^? ModelSignal<number>;
goToPage(page: number) {
  this.page.set(page);
}

private computePages() {
  return Array.from({ length: Math.ceil(this.collectionSize() / this.pageSize()) }, (_, i) => i + 1);
}

As you can see, a model() function is used to define the input/output pair, and the output emission is done using the set() method of the signal.

A model can be required, or can have a default value, or can be aliased, as it is the case for inputs. It can’t be transformed though. If you use an alias, the output will be aliased as well.

If you try to access the value of the model before it has been set, for example in the constructor of the component, then you’ll have a runtime error:

'NG0952: Model is required but no value is available yet.
Find more at https://angular.io/errors/NG0952'

Defer testing

The default behavior of the TestBed for testing components using @defer blocks has changed from Manual to Playthrough.

Check out our blog post about defer for more details.

NgOptimizedImage

The NgOptimizedImage directive (check out our blog post about it) can now automatically display a placeholder while the image is loading, if the provider supports automatic image resizing.

This can be enabled by adding a placeholder attribute to the directive:

<img ngSrc="logo.jpg" placeholder />

The placeholder is 30px by 30px by default, but you can customize it. It is displayed slightly blurred to give a hint to the user that the image is loading. The blur effect can be disabled with [placeholderConfig]="{ blur: false }.

Another new feature is the ability to use Netlify as a provider, joining the existing Cloudflare, Cloudinary, ImageKit, and Imgix providers.

Angular CLI

define support

The CLI now supports a new option named define in the build and serve targets. It is similar to what the esbuild plugin of the same name does: you can define constants that will be replaced with the specified value in TS and JS code, including in libraries.

You can for example define a BASE_URL that will be replaced with the value of https://api.example.com:

"build": {
  "builder": "@angular-devkit/build-angular:browser",
  "options": {
    "define": {
      "BASE_URL": "'https://api.example.com'"
    },

You can then use it in your code:

return this.http.get(`${BASE_URL}/users`);

TypeScript needs to know that this constant exists (as you don’t import it), so you need to declare it in a d.ts file:

declare const BASE_URL: string;

This can be an alternative to the environment files, and it can be even more powerful as the constant is also replaced in libraries.

Bun support

You can now use Bun as a package manager for your Angular CLI projects, in addition to npm, yarn, pnpm and cnpm. It will be automatically detected, or can be forced with --package-manager=bun when generating a new project.

clearScreen option

A new option is now supported in the application builder to clear the screen before rebuilding the application.

"build": {
  "builder": "@angular-devkit/build-angular:application",
  "options": {
    "clearScreen": true
  },

You then only see the output of the current build, and not from the previous one.

Abbreviated build targets

The angular.json file now supports abbreviated build targets. For example, you currently have something like this in your project:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "development": {
      "buildTarget": "app:build:development"
    },

This means that ng serve uses the app:build:development target to build the application.

This can now be abbreviated to:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "development": {
      "buildTarget": "::development"
    },

PostCSS support

The application builder now supports PostCSS, a tool for transforming CSS with JavaScript plugins. You just have to add a postcss.config.json or .postcssrc.json file to your project and the CLI will pick it up.

JSON build logs

The CLI now supports a new option to output the build logs in JSON format. This can be useful to integrate the build logs in other tools.

NG_BUILD_LOGS_JSON=1 ng build

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!


What's new in Angular 17.1?

Angular 17.1.0 is here!

Angular logo

This is a minor release with some nice features: let’s dive in!

TypeScript 5.3 support

Angular v17.1 now supports TypeScript 5.3. This means that you can use the latest version of TypeScript in your Angular applications. You can check out the TypeScript 5.3 release notes to learn more about the new features.

Inputs as signals

In Angular v17.1, a new feature was added to allow the use of inputs as signals. This is a first step towards signal-based components. The framework team added an input() function in @angular/core.

@Component({
  standalone: true,
  selector: 'ns-pony',
  template: `
    @if (ponyModel(); as ponyModel) {
      <figure>
        <img [src]="imageUrl()" [alt]="ponyModel.name" />
        <figcaption></figcaption>
      </figure>
    }
  `
})
export class PonyComponent {
  ponyModel = input<PonyModel>();
  imageUrl = computed(() => `assets/pony-${this.ponyModel()!.color}.gif`);
}

As you can see in the example above, the input() function returns a signal, that can be used in the template or in computed values (which would be the modern equivalent of ngOnChanges).

It can be undefined though, hence the @if in the template and the ! in the computed value.

If an input is mandatory, you can use the input.required() version of the function:

@Component({
  standalone: true,
  selector: 'ns-pony',
  template: `
    <figure>
      <img [src]="imageUrl()" [alt]="ponyModel().name" />
      <figcaption>{{ ponyModel().name }}</figcaption>
    </figure>
  `
})
export class PonyComponent {
  ponyModel = input.required<PonyModel>();
  imageUrl = computed(() => `assets/pony-${this.ponyModel().color}.gif`);
}

You can also provide a default value, an alias, and a transformer function. Here the ponySpeed field is aliased as speed, provided with a default value, and transformed to a number (even if the input is a string):

ponySpeed = input(10, {
  alias: 'speed',
  transform: numberAttribute
});

You can also use the signal as the source of an observable, to trigger an action when the input changes. For example, to fetch data from a server:

export class PonyComponent {
  ponyService = inject(PonyService);
  ponyId = input.required<number>();
  // entity fetched from the server every time the ponyId changes
  ponyModel = toSignal(toObservable(this.ponyId)
    .pipe(switchMap(id => this.ponyService.get(id))));
  imageUrl = computed(() => `assets/pony-${this.ponyModel()!.color}.gif`);
}

When coupled with the recent addition to the router called “Component Input Binding”, where the router binds the route parameters to the inputs of a component, it can lead to an interesting pattern. Note that the input transform is necessary as the router parameters are strings:

ponyId = input.required<number, string>({
  transform: numberAttribute
});

This behavior is enabled via withComponentInputBinding in the router configuration:

provideRouter(
  [
    {
      path: 'pony/:ponyId',
      component: PonyComponent
    }
  ],
  withComponentInputBinding()
),

Zoneless change detection

The framework is making progress towards zoneless change detection. A new private API called ɵprovideZonelessChangeDetection was added to @angular/core. When you add this provider to your application, the framework no longer relies on Zone.js for change detection (and you can remove it from the application).

So how does it work? Every time an event is fired, an input is set, an output emits a value, an async pipe receives a value, a signal is set, markForCheck is called, etc., the framework notifies an internal scheduler that something happened. It then runs the change detection on the component marked as dirty. But this doesn’t catch what Zone.js usually does: a setTimeout, a setInterval, a Promise, an XMLHttpRequest, etc.

But that shouldn’t be a problem because the idea is that when a setTimeout, setInterval or XMLHttpRequest callback is triggered, and you want it to update the state of the application, you should do it by modifying a signal, which will in turn trigger change detection.

This is far from being complete, as the “private API” part suggests. However, it indicates that the framework is making progress towards zoneless change detection.

Router

The router now has an info option in the NavigationExtras that can be used to store information about the navigation. Unlike the state option, this information is not persisted in the session history. The RouterLink directive now supports this option as well:

<a [routerLink]="['/pony', pony.id]" [info]="{ ponyName: pony.name }"></a>

Control flow migration

The control flow migration is still experimental but has been improved with a ton of bug fixes and new features. It now removes the useless imports from your component imports after the migration. It also now has a new option format to reformat your templates after the migration. The option is true by default, but can be turned off:

ng g @angular/core:control-flow --path src/app/app.component.html --format=false

INFINITE_CHANGE_DETECTION

This is not a new feature, but this bug fix is worth mentioning. Angular v17.1 fixes a bug for transplanted views, but this will also be useful for signals.

The framework now runs change detection while there are still dirty views to be refreshed in the tree. If too many loops are detected, the framework will throw an error: INFINITE_CHANGE_DETECTION.

This will remind the oldest Angular developers of the good old days of AngularJS, when we had to be careful with infinite digest loops 👴.

Angular v17.1 will throw this error if you have 100 loops in a row at the moment.

Angular CLI

Vite v5

The Angular CLI v17.1 now uses Vite v5 under the hood. Vite v5 was recently released, you can read more about it in the official blog post.

Application builder migration

If you haven’t migrated to the new application builder yet, there is now a migration schematic to help you with that:

ng update @angular/cli --name=use-application-builder

Keyboard shortcuts in dev server

After running ng serve, you can now see in the terminal the following line:

Watch mode enabled. Watching for file changes...
  ➜  Local:   http://localhost:4200/
  ➜  press h + enter to show help

If you press ‘h + enter’, you will see the list of available keyboard shortcuts:

Shortcuts
press r + enter to force reload browser
press u + enter to show server url
press o + enter to open in browser
press c + enter to clear console
press q + enter to quit

Quite cool!

Running tests with Web Test Runner

An experimental builder is now available to run tests with Web Test Runner. It is very early stage, but you can try it out by replacing the karma builder with web-test-runner in the angular.json file:

"test": {
  "builder": "@angular-devkit/build-angular:web-test-runner",
}

You then need to install the @web/test-runner package, and here you go! Running ng test will now use Web Test Runner instead of Karma (and bundle the files with the application builder, which uses esbuild, and not Webpack as the current karma builder does).

A lot of options aren’t available yet, so you can’t change the browser for example (it only runs in Chrome for now), or define reporters, or use any kind of configuration.

In the future, we will be able to define a configuration file for Web Test Runner, use other browsers (WTR supports using Playwright to download and run tests in other browsers), etc.

This builder will probably be the default in the future, as Karma is now deprecated.

loader option

The application builder gained a new loader option. It allows defining the type of loader to use for a specified file extension. The file matching the extension can then be used within the application code via an import.

The available loaders that can be used are:

  • text which treats the content as a string
  • binary which treats the content as a Uint8Array
  • file which emits the file and provides the runtime location of the file
  • empty which considers the content to be empty and will not include it in bundles

For example, to inline the content of SVG files into the bundled application, you can use the following configuration in the angular.json file:

loader: {
    ".svg": "text"
}

Then an SVG file can be imported in your code with:

import content from './logo.svg';

TypeScript needs to be aware of the module type for the import to prevent type-checking errors during the build, so you’ll need to add a type definition for the SVG file:

declare module "*.svg" {
  const content: string;
  export default content;
}

Output location

It is now possible to customize the output location of the build artifacts:

"outputPath": {
  "base": "dist/my-app",
  "browser": "",
  "server": "node-server",
  "media": "resources"
}

Retain special CSS comments

By default, the CLI removes comments from CSS files during the build. If you want to retain them because you use some tools that rely on them, you can now set the removeSpecialComments option to false in the optimization section of your angular.json file:

"optimization": {
  "styles": {
    "removeSpecialComments": false
  }
}

Allowed CommonJS dependencies

You can now specify * as a package name in the allowedCommonJsDependencies option to allow all packages in your build:

"allowedCommonJsDependencies": ["*"]

–no-browsers in tests

You can now use the --no-browsers option when running tests with the CLI. This will prevent the browser from opening when running tests, which can be useful if you are inside a container for example. This was already possible by setting the browsers option to [] in the karma.conf.js file, but not from the CLI command.

ng test --no-browsers

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!


2023-12-29

What's new in Vue 3.4?

Vue 3.4.0 is here!

Vue logo

The last minor release was v3.3.0 in May. Since then, we have seen a few patch releases, some coming with new features.

Let’s see what we have in this release!

v-bind shorthand syntax

It is now possible to use a shorthand syntax for v-bind when the key and value have the same name!

<!-- before -->
<div v-bind:id="id"></div>
<-- or -->
<div :id="id"></div>

<!-- after -->
<div v-bind:id></div>
<-- or -->
<div :id></div>

Performances improvements for the reactivity system

Johnson Chu, the author of Volar, has done massive work to improve the performance of the reactivity system.

Let’s consider a scenario where you have a computed A that depends on a computed B. In Vue v3.3, if B is re-evaluated, A is also re-evaluated, even if B has the same value as before. In Vue v3.4, A is not re-evaluated if B has the same value as before. This is also true for watch functions.

Other improvements have been made for Arrays mutations, for watchers that depend on multiple computed values, and more (as you can see in the PR description).

This should avoid a whole lot of unnecessary re-renders! 🚀 (and hopefully, don’t introduce any regression 🤞).

computed previous value

You can now get the previous value in a computed, as the first parameter of the getter function.

const count = ref(0);
const double = computed((prev) => {
  console.log(prev);
  return count.value * 2
});
count.value++;
// logs 0

This can be useful if you want to manually compare object values. (computed internally uses Object.is to compare the previous and current values, which is not always what you want, see the PR description). This is especially useful with the new reactivity system improvements. In v3.4, a computed property will only trigger effects when its computed value has changed from the previous one. But in the case of a computed that return new objects, Vue thinks that the previous and current values are different. If you want to avoid triggering effects in that case, you can compare the previous and current values manually.

Performances improvements for the compiler

The Vue compiler has been improved to be faster. Evan rewrote the parser entirely, to avoid using regexes. The code generation has also been improved. They are now nearly 2 times faster!

This should not have a huge impact on your build times, as the Vue compiler is not the only step in the build process (you usually have the TypeScript compiler, the CSS preprocessor, etc.).

Support for import attributes

It is now possible to use import attributes in SFC (both in JS and TS):

import json from "./foo.json" with { type: "json" }

The support for using has also been added (new feature for explicit resource management in JS, see the proposal here).

watch once

The watch function gained a new option called once. When set to true, the watcher is removed after the first call.

watch('foo', () => {
  console.log('foo changed');
}, { once: true });

It was previously possible to achieve the same result by using the returned stop function:

const stop = watch('foo', () => {
  console.log('foo changed');
  stop();
});

Props validation

As you probably know, Vue provides a mechanism to validate props.

defineProps({
  min: {
    type: Number,
    required: true,
    validator: (value) => value >= 0,
  },
  max: {
    type: Number,
    required: true,
    validator: (value) => value >= 0,
  }
})

In the above example, the min and max props must be positive numbers. In Vue v3.4, the validator function is now called with a second argument containing all the props, allowing to validate the value against other props.

defineProps({
  min: {
    type: Number,
    required: true,
    validator: (value) => value >= 0,
  },
  max: {
    type: Number,
    required: true,
    validator: (value, props) => value >= props.min,
  }
})

Then if you try to use the component with max being lower than min, you will get a warning.

Invalid prop: custom validator check failed for prop "max".

SSR hydration mismatch warnings

When using SSR, the client-side hydration will now warn you with a message that includes the mismatching element. It was sometimes hard to find the mismatching element in the DOM, as the warning was in v3.3:

[Vue warn]: Hydration completed but contains mismatches.

In v3.4, the warning now contains the actual element (not only its tag name but the actual DOM element, so you can click on it), allowing us to see where it is in the DOM and why it failed.

[Vue warn]: Hydration text content mismatch in <h2>:
- Server rendered: Hello server
- Client rendered: Hello client

Vue now also warns you if you have a mismatch in classes, styles, or attributes!

You can enable this feature in production as well by using a feature flag in your Vite config called __VUE_PROD_HYDRATION_MISMATCH_DETAILS__:

export default defineConfig({
  plugins: [vue()],
  define: {
    __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: true 
  }
});

MathML support

It is now possible to write templates using MathML (in addition to HTML and SVG)!

The template below displays a beautiful :

<template>
  <math>
    <mrow><msup><mi>x</mi><mn>2</mn></msup></mrow>
  </math>
</template>

defineModel

The defineModel function was introduced as an experimental API in v3.3, is now a stable API. It is now the recommended way to define custom v-models.

Compared to what we explained in our previous blog post, the local option has been removed (see this discussion if you want to know why). The model now automatically adapts based on whether the parent provides a v-model or not.

Another change it that it is now possible to handle modifiers. For example, if you want to handle the .number modifier, you can do:

const [count, countModifiers] = defineModel({
  set(value) {
    if (countModifiers?.number) {
      return Number(value);
    }
    return value;
  }
});
console.log(countModifiers?.number); // true if the .number modifier is used

You can type the modifiers by using defineModel<number, 'number'>({ ... }). The first type parameter is the type of the model value, and the second one is the type of the modifiers (which can be a union type if you want to handle several ones).

You can play with this demo to see how it works.

TypeScript improvements

An effort has been made to sanitize the types (which will be helpful for all libraries in the ecosystem).

A notable improvement for developers is that app.directive, used to register global directives, can now be properly typed:

app.directive<HTMLElement, string>('custom', {
  mounted(el, binding) {
    // el is correctly typed as HTMLElement
    // binding is correctly typed as string
  }
})

Deprecated features removed

The reactivity transform experiment has been removed. It had been deprecated in v3.3.0 (see our previous blog post).

Vnode hook events written like vnodeMounted have been deprecated in v3.3 (see our previous blog post) and they are now no longer supported. You should use the @vue: syntax instead, like @vue:mounted.

The v-is directive has also been removed.

News from the ecosystem

Vue 2 End of Life

Vue 2 has reached its end of life, and Evan wrote a blog post about it:

👉 https://blog.vuejs.org/posts/vue-2-eol

Vapor mode

Vapor (@vue/vapor) is making progress with a new repository.

For now, it introduces two work-in-progress packages: a new compiler and a new runtime. They only support the most basic features at the moment, and aren’t easily usable. There is a playground in the repository if you want to try it out.

The biggest difference with Vue 3 is that Vapor generates a rendering function that does not rely on virtual DOM.

For example, the following component:

<script setup lang="ts">
import { ref, computed } from 'vue/vapor'

const count = ref(1)
const double = computed(() => count.value * 2)

const inc = () => count.value++
</script>

<template>
  <div>
    <h1 class="red">Counter</h1>
    <div>8 * 2 = </div>
    <button @click="inc">inc</button>
  </div>
</template>

generates the following render function:

function _sfc_render(_ctx) {
  const t0 = _template('<div><h1 class="red">Counter</h1><div> * 2 = </div><button>inc</button></div>');
  const n0 = t0();
  const { 0: [, { 1: [n3], 2: [n4] }] } = _children(n0);
  const n1 = _createTextNode(_ctx.count);
  const n2 = _createTextNode(_ctx.double);
  _prepend(n3, n1);
  _append(n3, n2);
  _on(n4, "click", (...args) => _ctx.inc && _ctx.inc(...args));
  _watchEffect(() => {
    _setText(n1, void 0, _ctx.count);
  });
  _watchEffect(() => {
    _setText(n2, void 0, _ctx.double);
  });
  return n0;
}

As you can see the render function is using a different strategy than Vue 3: it creates the static elements, then it creates the dynamic elements, and finally it updates the dynamic elements when needed using watchEffect.

You can check in the project’s README the features that are supported and the ones that are not.

Vue Test Utils

VTU should now have better type-checking support for TypeScript users. For example wrapper.setProps({ foo: 'bar' }) will now correctly error if the component has no foo prop.

create-vue

create-vue now generates projects using Vite v5, which was recently released.

Nuxt

Nuxt v3.9 is out as well, with the support of Vue 3.4. It brings a lot of new features and experiments: you can read more in the official blog post.

That’s all for this release. Stay tuned for the next one!

Our ebook, online training and training) are up-to-date with these changes if you want to learn more!


What's new in Angular 17?

Angular v17 is here!

Angular logo

For French-speaking people, I talked about the release on the Angular Devs France YouTube channel.

This is a major release packed with features: let’s dive in!

angular.dev

The Angular team has been cranking it communication-wise lately, with a live event to unveil the new features of Angular v17, and a new website called angular.dev, which will be the future official website. It features the same documentation but with a new interactive tutorial, and a playground to try Angular without installing anything (as Vue or Svelte do as well).

Angular also has a new logo that you can see at the top of this post!

Control flow syntax

Even if it is only a “developer preview” feature, this is a big one! Angular templates are evolving to use a new syntax for control flow structures.

We wrote a dedicated blog post about this feature:

👉 Angular Control Flow Syntax

An experimental migration allows you to give it a try in your project. The syntax should become stable in v18, and be the recommended way to write templates at that point.

Deferrable views

Another big feature is the introduction of deferrable views using @defer in templates.

We wrote a dedicated blog post about this feature:

👉 Angular Deferrable Views

This is a “developer preview” feature as well and should become stable in v18. It’s probably going to be less impactful than the control flow syntax, but it’s still interesting to have a way to easily lazy-load parts of a template.

Signals are now stable!

The Signals API is now marked as stable 🎉. Except effect(), and the RxJS interoperability functions toSignal and toObservable which might change and are still marked as “developer preview”.

The API has not changed much since our blog post about Signals, but some notable things happened.

mutate has been dropped

mutate() has been dropped from the API. You were previously able to write something like:

users.mutate(usersArray => usersArray.push(newUser));

And you’ll now have to write:

users.update(usersArray => [...usersArray, newUser]);

The mutate() method was introducing some issues with other libraries, and was not worth the trouble as it can be replaced by update() quite easily.

template diagnostic

A new compiler diagnostic is available to help you spot missing signal invocations in your templates.

Let’s say you have a count signal used in a template, but forgot the ():

<div>{{ count }}</div>

throws with:

NG8109: count is a function and should be invoked: count()

flushEffects

A new method is available (as a developer preview) on the TestBed class to trigger pending effects: flushEffects

TestBed.flushEffects();

This is because effect timing has changed a bit: they are no longer triggered by change detection but scheduled via the microtask queue (like setTimeout() or Promise.resolve()). So while you could previously trigger them by calling detectChanges() on the fixture, you now have to call TestBed.flushEffects().

afterRender and afterNextRender phases

The afterRender and afterNextRender functions introduced in Angular v16.2 can now specify a phase option. Angular uses this phase to schedule callbacks to improve performance. There are 4 possible values, and they run in the following order:

  • EarlyRead (when you need to read the DOM before writing to the DOM)
  • Write (needed if you want to write to the DOM, for example, to initialize a chart using a third-party library)
  • MixedReadWrite (default, but should be avoided if possible to use a more specific phase)
  • Read (recommended if you only need to read the DOM)

I think we should be able to use Read and Write in most cases. EarlyRead and MixedReadWrite degrade performances, so they should be avoided if possible.

export class ChartComponent {
  @ViewChild('canvas') canvas!: ElementRef<HTMLCanvasElement>;

  constructor() {
    afterNextRender(() => {
      const ctx = this.canvas.nativeElement;
      new Chart(ctx, { type: 'line', data: { ... } });
    }, { phase: AfterRenderPhase.Write });
  }
}

Performances

The internal algorithm changed to use a ref-counting mechanism instead of a mechanism based on bi-directional weak references. It should be more performant than it was in many cases.

It’s also worth noting that the change detection algorithm has been improved to be more efficient when using Signals. Previously, when reading a signal in a template, Angular was marking the component and all its ancestors as dirty when the signal was updated (as it currently does with when OnPush components are marked for check). It’s now a bit smarter and only marks the component as dirty when the signal is updated and not all its ancestors. It will still check the whole application tree, but the algorithm will be faster because some components will be skipped.

We don’t have a way to write pure signal-based components yet, with no need for ZoneJS, but it should be coming eventually!

styleUrls as a string

The styleUrls and styles properties of the @Component decorator can now be a string instead of an array of strings. A new property called styleUrl has also been introduced.

You can now write:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css',
})
export class AppComponent {}

View Transitions router support

The View Transitions API is a fairly new browser API that allows you to animate the transition between two views. It is only supported in recent versions of Chrome, Edge, and Opera (see caniuse.com stats) but not in Firefox yet. It works by taking a screenshot of the current view and animating it to the new view.

I’m not very familiar with this API, but there is a great article about it on developer.chrome.com and cool demos on this site (open it with a browser that supports this API of course).

Angular v17 adds support for this API in the router. This is an experimental feature, and you’ll have to enable it by using withTransitionViews():

bootstrapApplication(AppComponent, { 
  providers: [{ provideRouter(routes, withTransitionViews()) }] 
});

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.

It is possible to skip the initial transition by using the skipInitialTransition option:

bootstrapApplication(AppComponent, { 
  providers: [{ provideRouter(routes, withTransitionViews({ skipInitialTransition: true })) }] 
});

More advanced scenarios require to add/remove CSS classes to the views, so the router also lets you run an arbitrary function when the transition is done if you use the onViewTransitionCreated option to define a callback.

Http

The fetch backend (introduced in Angular v16.1) has been promoted to stable.

When using SSR, it is now possible to customize the transfer cache, using withHttpTransferCacheOptions(options). The options can be:

  • filter: a function to filter the requests that should be cached
  • includeHeaders: the list of headers to include (none by default)
  • includePostRequests: whether or not to cache POST requests (by default only GET and HEAD requests are cached)

For example:

bootstrapApplication(AppComponent, { 
  providers: [provideHttpClient({
    withHttpTransferCacheOptions({ includePostRequests: true })
  })
});

Devtools

The devtools received some love as well, and they now allow you to inspect the dependency injection tree.

Animations

No new feature for this part of Angular, but it is now possible to lazy-load the animations package. In a standalone application, you can use provideAnimationsAsync() instead of using provideAnimations() and the necessary code for animations will be loaded asynchronously.

The application should work the same, but you should see an extra chunk appear when building the application. That’s a few kilobytes of JavaScript that you don’t have to load upfront 🚀.

You can disable animations by providing 'noop' as the value of provideAnimationsAsync():

bootstrapApplication(AppComponent, { 
  providers: [provideAnimationsAsync('noop')] 
});

Performances

In dev mode, you’ll now get a warning if you load an oversized image or if an image is the “Largest Contentful Paint element” in the page and is lazy-loaded (which is a bad idea, see the explanations here).

For example:

An image with src image.png has intrinsic file dimensions much larger than its 
rendered size. This can negatively impact application loading performance. 
For more information about addressing or disabling this warning, see  
https://angular.io/errors/NG0913

You can configure this behavior via dependency injection, for example, if you want to turn off these warnings:

{
  provide: IMAGE_CONFIG, useValue:
  {
    disableImageSizeWarning: false,
    disableImageLazyLoadWarning: false
  }
}

TypeScript 5.2 and Node.js v18

It’s worth noting that Angular now requires TypeScript 5.2 and Node.js v18. Support for older versions has been dropped.

Angular CLI

A lot happened in the CLI!

👉 Check out our dedicated blog post about the CLI v17 for more details.

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!


What's new in Angular CLI 17.0?

Angular CLI 17.0.0 is out!✨

If you want to upgrade to 17.0.0 without pain (or to any other version, by the way), I have created a Github project to help: angular-cli-diff. Choose the version you’re currently using (16.2.0 for example), and the target version (17.0.0 for example), and it gives you a diff of all files created by the CLI: angular-cli-diff/compare/16.2.0…17.0.0. It can be a great help along with the official ng update @angular/core @angular/cli command. You have no excuse for staying behind anymore!

Let’s see what we’ve got in this release.

Standalone applications with Vite by default!

The --standalone flag is now the default behavior of the CLI. This means generating a new project with ng new now uses standalone components by default, and that the ng generate component/pipe/directive command now generates standalone components/pipes/directives.

Another notable change to ng new is that the routing is now enabled by default.

But the most important change is that the CLI now uses Vite out-of-the-box! A new builder called application has been introduced, and is used when generating a new project. This builder has a very similar configuration to the browser builder, so the migration is quite easy if you want to use Vite in an existing project You have to change the builder from browser to application in the angular.json file, rename the main property to browser, and remove a few options from the development configuration (buildOptimizer, vendorChunk).

Once migrated, the ng serve command will use Vite instead of Webpack. Build time should be faster, especially for cold starts (I saw 2-3x times improvement on my machine). There is no HMR by default yet, but the global style changes are detected and applied automatically without reloading the page.

Note that the output of the ng build Vite-based command is now in dist/my-project/browser instead of dist/my-project.

The browser-esbuilder builder still exists, but will be removed in the future. You should use the application builder instead.

ng new –ssr

A new flag --ssr has been added to the ng new command to generate a new project with SSR enabled out of the box.

It generates a project similar to what you usually get and then runs the @angular/ssr schematics (you can also use the schematics directly on an existing project with ng add @angular/ssr). @angular/ssr is a new package and replaces the Angular Universal package. If you were using the Angular Universal package, ng update migrates your configuration to use @angular/ssr automatically.

This schematic does the following:

  • adds the @angular/ssr package
  • adds the @angular/platform-server package
  • adds the express and @types/express packages
  • adds the main.server.ts file (entry point for the application when running on the server)
  • adds the app.config.server.ts file (providers for the application when running on the server)
  • adds the tsconfig.server.json file
  • adds the server.ts file (the Express server, responsible for serving the application)

It updates the angular.json configuration to add the following options to the build target:

"server": "src/main.server.ts",
"prerender": true,
"ssr": {
  "entry": "server.ts"
}

and adds the provideClientHydration() to the (browser) application providers, to have a smooth transition between the server and the client. This is a new feature of Angular v16, and we talked about it in our article about the v16 release.

When running ng build, the CLI will now build the server bundle (in dist/my-project/server) and the client bundle (in dist/my-project/browser). You can then run the generated server with:

node dist/my-project/server/main.server.mjs

This starts an Express server on port 4000 by default, which serves the rendered pages.

The rendered pages are in the browser folder, and are named ${page}/index.html:

dist/my-project/browser/index.html
dist/my-project/browser/login/index.html
dist/my-project/browser/register/index.html

If you use localize in your application, the CLI will also build the localized bundles (in dist/my-project/server/${lang}).

The prerendering mechanism should be quite accurate now, as it uses the Angular router under the hood to navigate to each route and render it (routes with parameters or redirections are skipped). When prerendering is enabled, the CLI generates a prerendered-routes.json file that contains all the prerendered routes. This is useful if you deploy on the cloud as this file is usually recognized by providers to serve these files as static.

{
  "routes": [
    "/",
    "/login",
    "/register"
    ...
  ]
}

You can disable the auto-discovery of routes by setting the discoverRoutes option to false in the angular.json file. You can also provide your own list of routes in this file by defining routeFiles:

"ssr": {
  "discoverRoutes": false,
  "routeFiles": "ssg-routes.txt"
}

This file must contain a list of routes that you want to render (and can contain parameterized routes).

When running ng serve, the CLI serves the application via Vite, and only pre-renders the requested page (the one you’re currently on).

You can also use a new option to CommonEngine called enablePerformanceProfiler to trace the performance of each step of the rendering:

const commonEngine = new CommonEngine({
  enablePerformanceProfiler: true
});

When using SSR, it is recommended to use the Fetch version of the HTTP client, by using provideHttpClient(withFetch()) (as introduced in Angular v16.1). This is for performance and compatibility reasons.

NG02801: Angular detected that `HttpClient` is not configured to use `fetch` APIs. It's strongly recommended to enable `fetch` for applications that use Server-Side Rendering for better performance and compatibility. To enable `fetch`, add the `withFetch()` to the `provideHttpClient()` call at the root of the application.

Functional HTTP interceptors by default

The CLI now generates functional interceptors by default, without the need to specify --functional anymore. Class-based interceptors are still available with the --no-functional option, but you’re now encouraged to use the functional ones.

Summary

That’s all for the CLI v17.0 release! You’ll find more interesting features in our article about the framework v17.0.0 release.

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


A guide to Angular Deferrable Views with @defer

With the introduction of the Control flow syntax, the Angular team has also introduced a new way to load components lazily (as a developer preview for now). We already have lazy-loading in Angular, but it is mainly based on the router.

Angular v17 adds a new way to load components lazily, using the @defer syntax in your templates.

@defer lets you define a block of template that will be loaded lazily when a condition is met (with all the components, pipes, directives, and libraries used in this block lazily loaded as well). Several conditions can be used. For example, it can be “as soon as possible (no condition)”, “when the user scrolls to that section”, “when the user clicks on that button” or “after 2 seconds”.

Let’s say your home page displays a “heavy” ChartComponent that uses a charting library and some other dependencies, like a FromNow pipe:

@Component({
  selector: 'ns-chart',
  template: '...',
  standalone: true,
  imports: [FromNowPipe],
})
export class ChartComponent {
  // uses chart.js
}

This component is used in the home page:

import { ChartComponent } from './chart.component';

@Component({
  selector: 'ns-home',
  template: `
    <!-- some content -->
    <ns-chart />
  `,
  standalone: true,
  imports: [ChartComponent]
})
export class HomeComponent {
  // ...
}

When the application is packaged, the ChartComponent will be included in the main bundle:

+------------------------+
| main-xxxx.js  -  300KB |
+------------------------+
| home.component.ts      |
| chart.component.ts     |
| from-now.pipe.ts       |
| chart.js               |
+------------------------+

Let’s say that the component is not visible at first on the home page, maybe because it is at the bottom of the page, or because it is in a tab that is not active. It makes sense to avoid loading this component eagerly because it would slow down the initial loading of the page.

With @defer, you can load this component only when the user really needs it. Just wrapping the ChartComponent in a @defer block will do the trick:

import { ChartComponent } from './chart.component';

@Component({
  selector: 'ns-home',
  template: `
    <!-- some content -->
    @defer (when isVisible) {
      <ns-chart />
    }
  `,
  standalone: true,
  imports: [ChartComponent]
})

The Angular compiler will rewrite the static import of the ChartComponent to a dynamic import (() => import('./chart.component')), and the component will be loaded only when the condition is met. As the component is now imported dynamically, it will not be included in the main bundle. The bundler will create a new chunk for it:

+------------------------+
| main-xxxx.js  -  100KB |
+------------------------+       +-------------------------+
| home.component.ts      |------>| chunk-xxxx.js - 200KB   |
+------------------------+       +-------------------------+
                                 | chart.component.ts      |
                                 | from-now.pipe.ts        |
                                 | chart.js                |
                                 +-------------------------+

The chunk-xxxx.js file will only be loaded when the condition is met, and the ChartComponent will be displayed.

Before talking about the various kinds of conditions that can be used with @defer, let’s see how to use another interesting feature: displaying a placeholder until the deferred block is loaded.

@placeholder, @loading, and @error

You can define a placeholder template with @placeholder that will be displayed until the loading condition is met. Then, while the block is loading, you can display a loading template with @loading. If no @loading block is defined, the placeholder stays there until the block is loaded. You can also define an error template with @error that will be displayed if the block fails to load.

@defer (when show) {
  <ns-chart />
}
@placeholder {
  <div>Something until the loading starts</div>
}
@loading {
  <div>Loading...</div>
}
@error {
  <div>Something went wrong</div>
}

When using server-side rendering, only the placeholder will be rendered on the server (the defer conditions will never trigger).

after and minimum

As the @defer block loading can be quite fast, there is a risk that the loading block is displayed and hidden too quickly, causing a “flickering” effect.

To avoid this, you can use the after option to specify after how many milliseconds the loading should be displayed.

If the block takes less than this delay to load, then the @loading block is never displayed.

You can also use the minimum option to specify a minimum duration for the loading. If the loading is faster than the minimum duration, then the loading will be displayed for the minimum duration (this only applies if the loading is ever displayed).

You can of course combine all these options:

@defer (when show) {
  <ns-chart />
}
@placeholder {
  <div>Something until the loading starts</div>
}
@loading (after 500ms; minimum 500ms) {
  <div>Loading...</div>
}

You can also specify a minimum duration for the placeholder. It can be useful when the loading condition is immediate (for example, when no condition is specified). In that case, the placeholder will be displayed for the minimum duration, even if the block is loaded immediately, to avoid a “flickering” effect.

@defer (when show) {
  <ns-chart />
}
@placeholder (minimum 500ms) {
  <div>Something until the loading starts</div>
}
@loading (after 500ms; minimum 500ms) {
  <div>Loading...</div>
}

Conditions

Several conditions can be used with @defer, let’s see them one by one.

No condition or on idle

The simplest condition is to not specify any condition at all: in this case, the block will be loaded when the browser is idle (the loading is scheduled using requestIdleCallback).

@defer {
  <ns-chart />
}

This is equivalent to using the on idle condition:

@defer (on idle) {
  <ns-chart />
}

Simple boolean condition with when

You can also use a boolean condition to load a block of the template with when. Here, we display the defer block only when the show property of the component is true:

@defer (when show) {
  <ns-chart />
}

Note that this is not the same as using *ngIf on the block, as the block will not be removed even if the condition becomes false later.

on immediate

The on immediate condition triggers the loading of the block immediately. It does not display a placeholder, even if one is defined.

on timer

The on timer condition triggers the loading of the block after a given duration, using setTimeout under the hood.

@defer (on timer(2s)) {
  <ns-chart />
}

on hover

Other conditions are based on user interactions. These conditions can specify the element of the interaction using a template reference variable, or none to use the placeholder element. In the latter case, the placeholder element must exist and have a single child element that will be used as the element of the interaction.

The on hover condition triggers the loading of the block when the user hovers the element. Under the hood, it listens to the mouseenter and focusin events.

<span #trigger>Hover me</span>

@defer (on hover(trigger)) {
  <ns-chart />
}

or using the placeholder element:

@defer (on hover) {
  <ns-chart />
}
@placeholder {
  <span>Hover me</span>
}

on interaction

The on interaction condition triggers the loading of the block when the user interacts with the element. Under the hood, it listens to the click and keydown events.

on viewport

The on viewport condition triggers the loading of the block when the element becomes visible in the viewport. Under the hood, it uses an intersection observer.

Multiple conditions

You can also combine multiple conditions using a comma-separated list:

<!-- Loads if the user hovers the placeholder, or after 1 minute -->
@defer (on hover, timer(60s)) {
  <ns-chart />
}
@placeholder {
  <span>Something until the loading starts</span>
}

Prefetching

@defer allows you to separate the loading of a component from its display. You can use the same conditions we previously saw to load a component using prefetch, and then display it with another condition.

For example, you can prefetch the lazy-loaded content on idle and then display it on interaction:

@defer (on interaction; prefetch on idle) {
  <ns-chart />
}
@placeholder {
  <button>Show me</button>
}

Note that the @loading block will not be displayed if the deferred block is already prefetched when the loading condition is met.

How to test deferred loading?

When a component uses defer blocks in its template, you’ll have to do some extra work to test it.

The TestBed API has been extended to help you with that. The configureTestingModule method now accepts a deferBlockBehavior option. By default, this option is set to DeferBlockBehavior.Manual, which means that you’ll have to manually trigger the display of the defer blocks. But let’s start with the other option instead.

You can change this behavior by using DeferBlockBehavior.Playthrough. Playthrough means that the defer blocks will be displayed automatically when a condition is met, as they would when the application runs in the browser.

beforeEach(() => {
  TestBed.configureTestingModule({
    deferBlockBehavior: DeferBlockBehavior.Playthrough
  });
});

In that case, the defer blocks will be displayed automatically when a condition is met, after calling await fixture.whenStable().

So if we test a component with a deferred block that is visible after clicking on a button, we can use:

// Click the button to trigger the deferred block
fixture.nativeElement.querySelector('button').click();
fixture.detectChanges();

// Wait for the deferred block to render
await fixture.whenStable();

// Check its content
const loadedBlock = fixture.nativeElement.querySelector('div');
expect(loadedBlock.textContent).toContain('Some lazy-loaded content');

If you want to use the DeferBlockBehavior.Manual behavior, you’ll have to manually trigger the display of the defer blocks. To do so, the fixture returned by TestBed.createComponent now has an async getDeferBlocks method that returns an array of DeferBlockFixture objects. Each of these fixtures has a render method that you can call to display the block in a specific state, by providing a DeferBlockState parameter.

DeferBlockState is an enum with the following values:

  • DeferBlockState.Placeholder: display the placeholder state of the block
  • DeferBlockState.Loading: display the loading state of the block
  • DeferBlockState.Error: display the error state of the block
  • DeferBlockState.Complete: display the defer block as if the loading was complete

This allows a fine-grained control of the state of the defer blocks. If we want to test the same component as before, we can do:

const deferBlocks = await fixture.getDeferBlocks();
// only one defer block should be found
expect(deferBlocks.length).toBe(1);

// Render the defer block
await deferBlocks[0].render(DeferBlockState.Complete);

// Check its content
const loadedBlock = fixture.nativeElement.querySelector('div');
expect(loadedBlock.textContent).toContain('Some lazy-loaded content');

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


Angular templates got better - the Control Flow syntax

Angular v17 introduces a new “developer preview” feature called “control flow syntax”. This feature allows you to use a new template syntax to write control flow statements, like if/else, for, and switch, instead of using the built-in structural directives (*ngIf, *ngFor, and *ngSwitch).

To understand why this was introduced, let’s see how structural directives work in Angular.

Structural directives under the hood

Structural directives are directives that change the structure of the DOM by adding, removing, or manipulating elements. They are easy to recognize in Angular because they begin with an asterisk *.

But how do they really work?

Let’s take a simple template with ngIf and ngFor directives as an example:

<h1>Ninja Squad</h1>
<ul *ngIf="condition">
  <li *ngFor="let user of users">{{ user.name }}</li>
</ul>

If you read the chapter of our ebook about the Angular compiler, you know that the framework generates JavaScript code from this template. And maybe you imagine that *ngIf gets converted to a JavaScript if and *ngFor to a for loop like:

createElement('h1');
if (condition) {
  createElement('ul');
  for (user of users) {
    createElement('li');
  }
}

But Angular does not work exactly like that: the framework decomposes the component’s template into “views”. A view is a fragment of the template that has static HTML content. It can have dynamic attributes and texts, but the HTML elements are stable.

So our example generates in fact three views, corresponding to three parts of the template:

Main view:

<h1>Ninja Squad</h1>
<!-- special comment -->

NgIf view:

<ul>
  <!-- special comment -->
</ul>

NgFor view:

<li>{{ user.name }}</li>

This is because the * syntax is in fact syntactic sugar to apply an attribute directive on an ng-template element. So our example is the same as:

<h1>Ninja Squad</h1>
<ng-template [ngIf]="condition">
<ul>
  <ng-template ngFor [ngForOf]="users" let-user>
    <li>{{ user.name }}</li>
  </ng-template>
</ul>
</ng-template>

Here ngIf and ngFor are plain directives. Each ng-template then generates a “view”. Each view has a static structure that never changes. But these views need to be dynamically inserted at some point. And that’s where the <!-- special comment --> comes into play.

Angular has the concept of ViewContainer. A ViewContainer is like a box where you can insert/remove child views. To mark the location of these containers, Angular uses a special HTML comment in the created DOM.

That’s what ngIf actually does under the hood: it creates a ViewContainer, and then, when the condition given as input changes, it inserts or removes the child view at the location of the special comment.

This view concept is quite interesting as it will allow Angular to only update views that consume a signal in the future, and not the whole template of a component! Check out out our blog post about the Signal API for more details.

Custom structural directives

You can create your own structural directives if you want to. Let’s say you want to write a *customNgIf directive. You can create a directive that takes a condition as an input and injects a ViewContainerRef (the service that allows to create the view) and a TemplateRef (the ng-template on which the directive is applied).

import { Directive, DoCheck, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[customNgIf]',
  standalone: true
})
export class CustomNgIfDirective implements DoCheck {
  /**
  * The condition to check
  */
  @Input({ required: true, alias: 'customNgIf' }) condition!: boolean;

  /**
  * The view created by the directive
  */
  conditionalView: EmbeddedViewRef<any> | null = null;

  constructor(
    /**
    * The container where the view will be inserted
    */
    private vcr: ViewContainerRef,
    /**
    * The template to render
    */
    private tpl: TemplateRef<any>
  ) {}

  /**
  * This method is called every time the change detection runs
  */
  ngDoCheck() {
    // if the condition is true and the view is not created yet
    if (this.condition && !this.conditionalView) {
      // create the view and insert it in the container
      this.conditionalView = this.vcr.createEmbeddedView(this.tpl);
    } else if (!this.condition && this.conditionalView) {
      // if the condition is false and the view is created
      // destroy the view
      this.conditionalView.destroy();
      this.conditionalView = null;
    }
  } }

This works great! And as you can see, it lets developers like us create powerful structural directives if we want to: the built-in directives offered by Angular are not special in any way.

But this approach has some drawbacks: for example, it is a bit clunky to have an else alternative with *ngIf:

<div *ngIf="condition; else elseBlock">If</div>
<ng-template #elseBlock><div>Else</div></ng-template>

elseBlock is another input of the NgIf directive, of type TemplateRef, that the directive will display if the condition is falsy. But this is not very intuitive to use, so we often see this instead:

<div *ngIf="condition">If</div>
<div *ngIf="!condition">Else</div>

The structural directives are also not perfect type-checking-wise. Even if Angular does some magic (with some special fields called ngTemplateGuard in the directives to help the type-checker), some cases are too tricky to handle. For example, the “else” alternative of *ngIf is not type-checked:

<div *ngIf="!user; else userNotNullBlock">No user</div>
<ng-template #userNotNullBlock>
  <div>
    <!-- should compile as user is not null here -->
    <!-- but it doesn't -->
    {{ user.name }}
  </div>
</ng-template>

NgSwitch is even worse, as it consists of 3 separate directives NgSwitch, NgSwitchCase, and NgSwitchDefault. The compiler has no idea if the NgSwitchCase is used in the right context.

<!-- user.type can be `'user' | 'anonymous'` -->
<ng-container [ngSwitch]="user.type">
  <div *ngSwitchCase="'user'">User</div>
  <!-- compiles even if user.type can't be 'admin' -->
  <div *ngSwitchCase="'admin'">Admin</div>
  <div *ngSwitchDefault>Unknown</div>
</ng-container>

It’s also worth noting that the * syntax is not very intuitive for beginners. And structural directives depend on the ngDoCheck lifecycle hook, which is tied to zone.js. In a future world where our components use the new Signal API and don’t need zone.js anymore, structural directives would still force us to drag zone.js in our bundle.

So, to sum up, structural directives are powerful but have some drawbacks. Fixing these drawbacks would require a lot of work in the compiler and the framework.

That’s why the Angular team decided to introduce a new syntax to write control flow statements in templates!

Control flow syntax

The control flow syntax is a new syntax introduced in Angular v17 to write control flow statements in templates.

The syntax is very similar to some other templating syntaxes you may have met in the past, and even to JavaScript itself. There have been some debates and polling in the community about the various alternatives, and the @-syntax proposal won.

With the control flow syntax, our previous template with *ngIf and *ngFor can be rewritten as:

<h1>Ninja Squad</h1>
@if (condition) {
  <ul>
    @for (user of users; track user.id) {
      <li>{{ user.name }}</li>
    }
  </ul>
}

This syntax is interpreted by the Angular compiler and creates the same views as the previous template, but without the overhead of creating the structural directives, so it is also a tiny bit more performant (as it uses brand new compiled instructions under the hood in the generated code). As this is not directives, the type-checking is also much better.

And, cherry on the cake, the syntax is more powerful than the structural directives!

The drawback is that this syntax uses @, { and } characters with a special meaning, so you can’t use these characters in your templates anymore, and have to use equivalent HTML entities instead (\&#64; for @, \&#123; for {, and \&#125; for }).

If statement

As we saw above, a limitation of NgIf is that it is a bit clunky to have an else alternative. And we can’t have an else if alternative at all.

That’s no longer a problem with the control flow syntax:

@if (condition) {
  <div>condition is true</div>
} @else if (otherCondition) {
  <div>otherCondition is true</div>
} @else {
  <div>condition and otherCondition are false</div>
}

You can still store the result of the condition in a variable if you want to, which is really handy when used with an async pipe for example:

@if (user$ | async; as user) {
  <div>User is {{ user.name }}</div>
} @else if (isAdmin$ | async) {
  <div>User is admin</div>
} @else {
  <div>No user</div>
}

For statement

With the control flow syntax, a for loop needs to specify a track property, which is the equivalent of the trackBy function of *ngFor. Note that this is now mandatory, whereas it was optional with *ngFor. This is for performance reasons, as the Angular team found that very often, developers were not using trackBy when they should have.

<ul>
  @for (user of users; track user.id) {
    <li>{{ user.name }}</li>
  }
</ul>

As you can see, this is a bit easier to use than the trackBy function of *ngFor which requires to write a function. Here we can directly specify the property of the item that is unique, and the compiler will generate the function for us. If you don’t have a unique property, you can still use a function or just use the loop variable itself (which is equivalent to what *ngFor currently does when no trackBy is specified).

One of the very useful additions to the control flow syntax is the handling of empty collections. Previously you had to use an *ngIf to display a message if the collection was null or empty and then use *ngFor to iterate over the collection.

With the control flow syntax, you can do it with an @empty clause:

<ul>
  @for (user of users; track user.id) {
    <li>{{ user.name }}</li>
  } @empty {
    <li>No users</li>
  }
</ul>

We can still access the variables we used to have with *ngFor:

  • $index to get the index of the current item
  • $first to know if the current item is the first one
  • $last to know if the current item is the last one
  • $even to know if the current item is at an even index
  • $odd to know if the current item is at an odd index
  • $count to get the length of the collection

Unlike with *ngFor, you don’t have to alias these variables to use them, but you still can if you need to, for example when using nested loops.

<ul>
  @for (user of users; track user.id; let isOdd = $odd) {
    <li [class.grey]="isOdd">{{ $index }} - {{ user.name }}</li>
  }
</ul>

It is also worth noting that the control flow @for uses a new algorithm under the hood to update the DOM when the collection changes. It should be quite a bit faster than the algorithm used by *ngFor, as it does not allocate intermediate maps in most cases. Combined with the required track property, for loops should be way faster in Angular applications by default.

Switch statement

This is probably where the new type-checking shines the most, as using an impossible value in a case will now throw a compilation error!

@switch (user.type) {
  @case ('user') {
    <div>User</div>
  } @case ('anonymous') {
    <div>Anonymous</div>
  } @default {
    <div>Other</div>
  }
}

Note that the switch statement does not support fall-through, so you can’t have several cases grouped together. It also does not check if all cases are covered, so you won’t get a compilation error if you forget a case. (but I hope it will, add a 👍 on this issue if you want this as well!).

It’s also noteworthy that the @switch statement uses strict equality (===) to compare values, whereas *ngSwitch used to use loose equality (==). Angular v17 introduced a breaking change, and *ngSwitch now uses strict equality too, with a warning in the console during development if you use loose equality:

NG02001: As of Angular v17 the NgSwitch directive 
uses strict equality comparison === instead of == to match different cases. 
Previously the case value "1" matched switch expression value "'1'", 
but this is no longer the case with the stricter equality check.
Your comparison results return different results using === vs. ==
and you should adjust your ngSwitch expression and / or values
to conform with the strict equality requirements.

The future of templating 🚀

The control flow syntax is a new “developer preview” feature introduced in Angular v17, and will probably be the recommended way to write templates in the future (the plan is to make it stable in v18 once it has been battle-tested).

It doesn’t mean that structural directives will be deprecated, but the Angular team will likely focus on the control flow syntax in the future and push them forward as the recommended solution.

We will even have an automated migration to convert structural directives to control flow statements in existing applications. The migration is available in Angular v17 as a developer preview. If you want to give it a try, run:

ng g @angular/core:control-flow

This automatically migrates all your templates to the new syntax! You can also run the migration against a single file with the --path option:

ng g @angular/core:control-flow --path src/app/app.component.html

Even though the new control flow is experimental, v17 comes with a mandatory migration needed to support this new control flow syntax, which consists in converting the @, { and } characters used in your templates to their HTML entities. This migration is run automatically when you update the app with ng update.

The future of Angular is exciting!

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


Posts plus anciens