Drag-n-drop in Angular as Observable

Observables are really fantastic and I learned to love them. The concept may be intimidating at first, especially the whole RxJS landscape. But it definitely pays off.

Implementing drag and drop using Observables is actually quite simple and super handy. Here is my implementation. I also write for my future self, to save myself time. And I know, it will be useful for you as well.

import { fromEvent, mergeMap, Observable, takeUntil } from "rxjs";

export function getDragAndDropObservable(element: HTMLElement): Observable<Event> {
  const down = fromEvent(element, 'mousedown');
  const move = fromEvent(element, 'mousemove');
  const up = fromEvent(element, 'mouseup');

  const dragAndDrop = down.pipe(mergeMap(() => move.pipe(takeUntil(up))));
  return dragAndDrop;

Example of usage

// Somewhere in your component
// throttleTime is optional, but recommended for performance reasons
ngAfterViewInit(): void {
  .subscribe(event => {
    doSomething(event as MouseEvent);

Happy coding!