Prefetching with the @defer block

We’ve covered how to use @defer to lazy-load blocks of code in our Angular v17+ applications. We also touched on the different trigger options as well as the ability to create custom triggers with when.

Yet there’s more to uncover with the prefetch option:

The above code would display my-component when the user interacts with the web page, but it would prefetch the code on idle, meaning as soon as the browser isn’t busy doing anything else. That way, when the user starts interacting with the page, the component has already been downloaded (or is currently downloading) from the server, which speeds things up.

The nice thing about prefetch is that it supports the same triggers (idle, viewport, interaction, hover, immediate, timer) as the @defer block, which allows for lots of different possible customizations.

Code challenge #2 Solution

In yesterday’s code challenge, our application wasn’t displaying any data. There were two reasons for that problem:

  1. HttpClient was not provided in the application
  2. The change detection strategy OnPush wasn’t compatible with the data flow of the application

I’m including links to previous newsletter entries for deeper dives on the different topics involved in that solution. And there are quite a few subtleties to overcome.

Let’s tackle the first issue, which was providing the HTTP client. We can use one of the several utility functions for standalone app config, in our case, provideHttpClient:

The second problem can be solved in two different ways:

  1. Remove change detection onPush to use the default one instead
  2. Use the async pipe or Signals to trigger change detection in that OnPush component

Because it’s always better to use the async pipe, I’m going with that option in our template:

In our component class, I stored the Observable from our service instead of storing the data. No more constructor needed:

You can see that solution in action on Stackblitz here. We fixed our code and added some performance improvements as well by ensuring we can’t get into memory leaks and optimizing change detection for that component.

Code challenge #2: DI or not DI?

One of the cool things about teaching Angular, running an Angular certification program, and interacting with hundreds of developers (and code bases) all around the world is that I get to see a lot of good ideas but also a lot of repeated mistakes.

Today, I want to share a small code challenge inspired by mistakes seen over the past few weeks so you can learn from these examples and hopefully won’t make these same mistakes in the future.

Here is the code I want you to look at:

You can run it on Stackblitz here and fork the project to debug what’s wrong and make it work. Currently, this App component displays nothing at all, which is a problem.

I’ll give you a possible solution tomorrow. In the meantime, feel free to send me your solution if you want.

Angular Signals Workshop Next Week

It’s official! I’m running an Angular Signals Workshop next Thursday, December 14th, at 9 am US/Pacific time (12 pm US/Eastern – 6 pm Central European time). Registration and attendance are free by using this link, but your support is appreciated by buying me a coffee if you feel so inclined.

Of course, the more support I get, the more likely I am to organize similar events in the future. Just saying 😉

This workshop will be limited to 100 participants, so register as soon as possible to guarantee your spot. I’ll cover everything you need to know about Signals, starting from scratch and covering every single available Signal API in Angular 17. You’ll be able to ask questions, practice with a few exercises, and see me explain my solutions.

As a bonus, all exercises and examples will use recent Angular features such as the new control flow syntax, standalone components, the inject function, and more! That way, we’ll cover more than just Signals in the 2 hours we spend together that Thursday.

Here is the registration link again. Looking forward to seeing you there, and feel free to let me know if you have any questions before registering.

Local variables and the new block syntax

Earlier this year, I mentioned how the async pipe can become much more useful if we use a local variable instead of multiplying subscriptions to an Observable. In this example, we store the data we get from a subscription in the user variable:

While that syntax still works as is, you might want to use the new control flow syntax of Angular 17. Fortunately for us, it is possible to use local variables as well using the following syntax:

The only difference is the ; in the middle of the expression.

Using FormBuilder or FormControl?

When creating reactive forms with Angular, we have two options available. The most documented one is to inject the FormBuilder service and use it to generate your form’s structure:

FormBuilder makes perfect sense for forms that contain lots of elements. This service gives us methods that are factories for the following syntax, which is a lot more verbose:

Now, if you have a simple form with just one or two form controls, you don’t need FormBuilder. Declaring your FormControl “manually” is actually more manageable that way:

You can find an example of a single FormControl with custom validation here on Stackblitz.

How to cache HTTP requests with a service worker?

In the past few weeks, we’ve talked about how to cache data with HTTP interceptors, with Subjects, and with shareReplay.

While all these options work, they are intrusive and need additional code for your application. Another option doesn’t require touching your application code; it only requires additional configuration, and that’s using a service worker.

What’s a service worker?

A service worker is a small piece of Javascript code that runs in the browser independently from your application. A service worker can be an HTTP proxy between your front-end code and server. It can intercept all HTTP traffic between your Angular application and any remote server.

How to enable service workers in Angular?

Run the command: ng add @angular/pwa

That’s it! You can read more about what the command does in the official documentation. The idea is that instead of writing our service worker code, we let the Angular API take care of that and generate the service worker based on our config.

How to configure what to cache, and for how long?

Angular generates a file called ngsw-config.json. In that file, you can specify which URLs you want to cache, for how long, and if you wish to optimize for freshness (use the cache only if the application is offline) or performance (use the cache as much as possible even if the app is online).

For instance, data that doesn’t change very often (a list of countries or currencies) could be cached for weeks or months, while dynamic data (a list of Tweets or user preferences) could be cached for just a few minutes:

You can find a complete example of such ngsw-config.json here. The full documentation for all supported options can be found here.

Service workers are part of Progressive Web Apps (PWAs). If you want to learn more about that, here’s a quick PWA tutorial of mine.

Customized Deferred Loading with “when”

Last month, I introduced the defer block and its trigger options to perform lazy-loading of a template block with various options.

One of the most flexible ways to user defer is to use the when condition because it allows us to load some code based on a boolean value – which means we have complete control over when to switch that value to true.

Maybe we want to do it once we receive a response from the server or wait for the user to click on a button, or both, for instance:

Another interesting feature is that when can be combined with other triggers. In that case, the first condition to be met would lazy-load the block of code, acting similarly to a logical OR:

And, of course, we can still use a placeholder to display before the block is loaded, as illustrated above.

Make types from JSON samples

First, a quick announcement: I’m running a donation-based online Angular Signals Workshop on December 14th and January 18th. If you’re interested, feel free to show your interest here, and remember that you don’t have to pay anything if you don’t want to or can’t.

Earlier this year, I shared how to generate type definitions for Typescript using json2ts, but that website has disappeared. A suggested superior alternative is Quicktype, which can also create DTOs and has several config options.

Recently, I heard about another option called MakeTypes. It’s as simple as the two previous tools, and it can also be downloaded via npm to be part of your local development process if that’s what you want:

Again, all you need to do is copy-paste your sample JSON and get instant Typescript interfaces (or proxy classes) to use in your project. And if you don’t want to use a website to create your types, head to the NPM page to download the tool.