I saw recently that in Angular 17 you can simplify lazy loading by using the @defer
directive. I'm wondering how to use it exactly to refactor my old code. Today I need to use the router for that but i don't really need it anymore, right?
Let say i have an Angular app with a 2nd router-outlet
inside a component to display different content depending on a left menu. The content displayed come from others standalone components. My angular 16 code base for my component look like:
top.component.html
<div id="leftMenu">
<div (click)="loadContent('sub-a')">Button1</div>
<div (click)="loadContent('sub-b')">Button2</div>
</div>
<router-outlet></router-outlet>
top.component.ts
import { Component } from '@angular/core';
import { Router, RouterOutlet } from '@angular/router';
@Component({
selector: 'app-top',
templateUrl: './top.component.html',
styleUrls: ['./top.component.scss'],
standalone: true,
imports: [RouterOutlet]
})
export class TopComponent {
constructor(private router: Router) {}
loadContent(destination:string){
this.Router.navigate(['top', destination]);
}
}
top.routes.ts
import { Routes } from "@angular/router";
export default [{
path: '',
loadComponent: () => import('./top.component').then(m=>m.TopComponent),
children:[
{
path: 'sub-a',
loadComponent: () => import('./subA/sub-a.component').then(m=>m.SubComponentA)
},
{
path: 'sub-b',
loadComponent: () => import('./subB/sub-b.component').then(m=>m.SubComponentB)
}
]
}] as Routes;
How can i use @defer
to simplify that?
Deferrable view, defined with the
@defer
block is a declarative API to specify that a component is a template should be loaded later.It's not here to replace router based lazy-loading but more a complement when there is no specific route the deferred component.
The best example is a heavy component on a scrolled page.