typescript 47 lines · 8 steps

A hover-triggered preloading strategy in Angular

Defer loading a route's bundle until the user hovers its link, using an RxJS Subject as the trigger.

Explained by highlit
1import { Injectable, inject } from '@angular/core';
2import { PreloadingStrategy, Route } from '@angular/router';
3import { Observable, of, Subject } from 'rxjs';
4import { filter, switchMap, take } from 'rxjs/operators';
5 
6@Injectable({ providedIn: 'root' })
7export class HoverPreloadStrategy implements PreloadingStrategy {
8 private readonly hovered$ = new Subject<string>();
9 private readonly preloaded = new Set<string>();
10 
11 preload(route: Route, load: () => Observable<unknown>): Observable<unknown> {
12 const path = route.path ?? '';
13 
14 if (route.data?.['preload'] === 'eager') {
15 this.preloaded.add(path);
16 return load();
17 }
18 
19 return this.hovered$.pipe(
20 filter((target) => target === path && !this.preloaded.has(path)),
21 take(1),
22 switchMap(() => {
23 this.preloaded.add(path);
24 return load();
25 })
26 );
27 }
28 
29 onHover(path: string): void {
30 const normalized = path.replace(/^\//, '');
31 if (!this.preloaded.has(normalized)) {
32 this.hovered$.next(normalized);
33 }
34 }
35}
36 
37@Injectable()
38export class RouterLinkHoverDirective {
39 private readonly strategy = inject(HoverPreloadStrategy);
40 
41 handleMouseEnter(routerLink: string | unknown[]): void {
42 const path = Array.isArray(routerLink)
43 ? routerLink.join('/')
44 : String(routerLink);
45 of(path).subscribe((p) => this.strategy.onHover(p));
46 }
47}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A PreloadingStrategy lets you decide per-route when a lazy bundle actually loads.
  2. 2Returning an Observable that only emits on hover defers the load until an external event fires.
  3. 3Tracking loaded paths in a Set keeps preloads idempotent so a bundle is never fetched twice.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A hover-triggered preloading strategy in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code