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 { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
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.