typescript 55 lines · 8 steps

Drag-and-drop reordering with signals in Angular

A standalone Angular component reorders tasks via CDK drag-drop, updates signals optimistically, and rolls back if the save fails.

Explained by highlit
1import { Component, inject, signal } from '@angular/core';
2import { CdkDragDrop, DragDropModule, moveItemInArray } from '@angular/cdk/drag-drop';
3import { HttpClient } from '@angular/common/http';
4import { finalize } from 'rxjs';
5 
6interface Task {
7 id: string;
8 title: string;
9 position: number;
10}
11 
12@Component({
13 selector: 'app-task-list',
14 standalone: true,
15 imports: [DragDropModule],
16 template: `
17 <ul cdkDropList (cdkDropListDropped)="drop($event)" class="task-list">
18 @for (task of tasks(); track task.id) {
19 <li cdkDrag class="task" [class.saving]="saving()">
20 <span cdkDragHandle class="handle">≡</span>
21 {{ task.title }}
22 </li>
23 }
24 </ul>
25 `,
26})
27export class TaskListComponent {
28 private readonly http = inject(HttpClient);
29 
30 readonly tasks = signal<Task[]>([]);
31 readonly saving = signal(false);
32 
33 drop(event: CdkDragDrop<Task[]>): void {
34 if (event.previousIndex === event.currentIndex) return;
35 
36 const previous = this.tasks();
37 const reordered = [...previous];
38 moveItemInArray(reordered, event.previousIndex, event.currentIndex);
39 this.tasks.set(reordered.map((task, index) => ({ ...task, position: index })));
40 
41 this.persistOrder(this.tasks(), previous);
42 }
43 
44 private persistOrder(next: Task[], rollback: Task[]): void {
45 this.saving.set(true);
46 const payload = next.map(({ id, position }) => ({ id, position }));
47 
48 this.http
49 .patch('/api/tasks/reorder', { tasks: payload })
50 .pipe(finalize(() => this.saving.set(false)))
51 .subscribe({
52 error: () => this.tasks.set(rollback),
53 });
54 }
55}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Signals give you reactive state that the template re-renders from automatically when you call set.
  2. 2Optimistic UI updates feel instant but need a saved snapshot to restore on failure.
  3. 3finalize runs on both success and error, making it the right place to clear a loading flag.

Related explainers

typescript
import { Component, computed, DestroyRef, inject, input, output, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { interval, map, takeWhile } from 'rxjs';
 

How a signal-driven countdown works in Angular

signals reactivity rxjs
Intermediate 8 steps
typescript
type TokenType = "keyword" | "string" | "comment" | "number" | "text";
 
interface Token {
  type: TokenType;

How a regex tokenizer highlights code

tokenizer regex lexing
Intermediate 10 steps
typescript
type Middleware<TIn, TOut> = (ctx: TIn) => Promise<TOut> | TOut;
 
class Pipeline<TIn, TOut> {
  private constructor(private readonly run: Middleware<TIn, TOut>) {}

A type-safe async middleware pipeline

generics type-safety middleware
Advanced 9 steps
typescript
type Countdown = {
  days: number;
  hours: number;
  minutes: number;

Building a self-stopping countdown timer

date-math closures timers
Intermediate 9 steps
python
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

Busting template fragment caches in Django

caching signals cache-invalidation
Intermediate 4 steps
typescript
export function isValidCardNumber(input: string): boolean {
  const digits = input.replace(/[\s-]/g, "");
 
  if (!/^\d{12,19}$/.test(digits)) {

Validating card numbers with the Luhn check

luhn-algorithm checksum input-validation
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

Drag-and-drop reordering with signals in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code