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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A PreloadingStrategy lets you decide per-route when a lazy bundle actually loads.
- 2Returning an Observable that only emits on hover defers the load until an external event fires.
- 3Tracking loaded paths in a Set keeps preloads idempotent so a bundle is never fetched twice.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-hover-triggered-preloading-strategy-in-angular-explained-typescript-b24b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.