Deferrable views in Angular
Today we're going to explore a new feature in Angular 17 - deferrable views.
Angular 17 is game changer, and when we talk about bumping current projects to version 17 - using all new features and benefits you can quickly see that it will require a lot of refactoring, including both templates and components (deferrable views, signals, new control-flow syntax etc.)
And one of the Angular 17 features is deferrable views.
Deferrable views will help you reduce your bundle size and improve your user experience.
So, we're going to discuss how to use deferrable views and how to use them.
Let's get started.
Lazy Loading Before Angular 17
Before the deferrable option in Angular 17 we had a few different ways to reduce the initial bundle size of an Angular app.
The most common way was the router-based lazy loading.
When defining routes you could use a simple notation which instructions Angular that a specific chunk of your application could be loaded only when it was activated via the router.
This was often referred to as lazy-loading pieces of your Angular app. And looked like this.
const routes: Routes = [
{
path: 'items',
loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
}
];
And then the defer block came
Starting with Angular 17 the same lazy-loading ability came around with the new defer
block.
Just like this.
@defer {
<my-large-table/>
}
Now you get to write much less code and the intention of the code is extremely clear.
But there's more.
The capabilities of the defer
feature go way beyond this simple example.
Using the @loading block
W also have, for example the @loading
and @error
blocks.
Most likely, while the chunk is loading we would like to show a loader.
@defer {
<my-large-table/>
} @loading {
<img alt="loading" src="/img/loading.gif" />
}
The loading block can also take two optional parameters.
minimum
is to specify the minimum amount of time that this placeholder should be shownafter
is the amount of time to wait after loading begins before showing the loading template.
Both the minimum and after parameters are specified in time increments of milliseconds (ms) or seconds (s).
@defer {
<my-large-table/>
} @loading (after 100ms; minimum 1s) {
<img alt="loading" src="/img/loading.gif" />
}
Using the @error block
The @error block let's us declare what should be shown if for some reason the defer
block fails to load.
This of course is optional. But it looks something like this.
@defer {
<my-large-table/>
} @error {
<p>Please refresh the page or check your internet connection</p>
}
Deferring away
And that, my Angular friend, is how to get started with deferrable views in Angular.
If you enjoyed this article please share on your social media and with your colleagues and friends at work on your work chat.
And remember, the future of Angular is bright.
A huge shout-out to the Angular team for all the awesome features they've given us.
Daniel Kreider