Typescript enums and why I avoid them

As an Angular coach, I review a lot of Angular applications. One thing that I see in a lot of code bases is the use of Typescript enums to store a bunch of constants:

The above code creates a new type CompassDirection with four possible values: CompassDirection.North, CompassDirection.East, etc.

Each constant gets assigned a numerical value starting at 0, so in that example, CompassDirection.North is equal to 0, and CompassDirection.North is equal to 3.

These values can be customized, and we can use strings, objects, or anything we want instead of numbers:

And that’s about all you can do with enums in Typescript.

Why I avoid enums

I avoid enums because they’re neither convenient nor performant. For instance, this is what the last example gets compiled into by the Typescript compiler:

That’s not pretty, and it comes at the extra cost of all that code being downloaded in the browser and then interpreted, which impacts performance.

Also, enums aren’t very convenient to be used in component templates. If I want to use an enum in a component template, I need this additional code to make that type accessible on the component instance (the this reference):

Instead, we could use a union type:

We still get a type associated with specific values, but now this gets compiled into the following:

No, I didn’t forget anything in that black rectangle: Union types are like interfaces and don’t get compiled into anything, meaning they do not increase the size of your code base or impact performance. Also, since those types are just the union of other types (such as strings or numbers), these constants can be used as-is in a component template without needing to tweak our component class.

In other words, union types preserve type safety without degrading our app’s performance, which is a win-win.

Dynamic forms with FormArray

We’ve covered reactive and template-driven forms in the past. One of the nice features of reactive forms is the FormArray class. You can use FormArray for a form where the number of inputs is dynamic and can increase or decrease:

To achieve the above, we create a FormArray in our component and add a method so we can append new FormControls to that array:

Then, we use a @for block to display all controls of that array in our template, including a button to add new names to the list. Note that we store the index of each control in a local variable i:

We can even add support for the removal of form elements using the removeAt method of FormArray and the index of the element to remove:

And that’s it! We can check that the FormArray value is updated correctly with the following expression:

You can see that code in action on Stackblitz here. You can read this excellent guest post from Jennifer Wadella on my blog for more information on dynamic forms.

Typescript Cheatsheet: Type

A few months back, I shared a cheat sheet for Typescript Control Flow. Today, I want to share a cheat sheet on types, which are the main reason why Typescript is so useful.

A few interesting features that aren’t too well known:

  • The keyof operator and the Type[Property] illustrated in the Mapped Types section
  • One of my favorites: Union types and the even more powerful Template Union Types (bottom right corner of the cheat sheet)

You can click here to see the full-size cheatsheet.

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.