@molecule/app-file-dropzone-angular

Feature · file-dropzone · App (browser) · v2.0.1 · Apache-2.0

Drag-drop file upload area with click-to-browse, accept/size filtering, and a content slot

npm install @molecule/app-file-dropzone-angular

npm · Source on GitHub

How it works

@molecule/app-file-dropzone-angular is a ready-made file-dropzone feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import type { PickedFile } from '@molecule/app-filesystem'
import { FileDropzone } from '@molecule/app-file-dropzone-angular'

@Component({
  selector: 'app-avatar-upload',
  standalone: true,
  imports: [FileDropzone],
  template: `
    <div
      mol-file-dropzone
      accept="image/*"
      [maxSize]="5 * 1024 * 1024"
      [onFiles]="uploadAvatar"
      [onRejected]="showError"
    ></div>
  `,
})
export class AvatarUpload {
  avatar: PickedFile | null = null
  rejectedFiles: readonly PickedFile[] = []
  uploadAvatar = (files: readonly PickedFile[]): void => {
    this.avatar = files[0] ?? null
  }
  showError = (files: readonly PickedFile[]): void => {
    this.rejectedFiles = files
  }
}

Works with: @molecule/app-angular, @molecule/app-filesystem, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular file dropzone — drag-drop + click-to-browse file picker with accept / max-size filtering. Pure UI: it emits readonly PickedFile[] and the host app performs the actual upload.

Exports <FileDropzone> and its FileDropzoneProps. It is the Angular counterpart of @molecule/app-file-dropzone-react: same props and the same DOM for the same input.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import type { PickedFile } from '@molecule/app-filesystem'
import { FileDropzone } from '@molecule/app-file-dropzone-angular'

@Component({
  selector: 'app-avatar-upload',
  standalone: true,
  imports: [FileDropzone],
  template: `
    <div
      mol-file-dropzone
      accept="image/*"
      [maxSize]="5 * 1024 * 1024"
      [onFiles]="uploadAvatar"
      [onRejected]="showError"
    ></div>
  `,
})
export class AvatarUpload {
  avatar: PickedFile | null = null
  rejectedFiles: readonly PickedFile[] = []
  uploadAvatar = (files: readonly PickedFile[]): void => {
    this.avatar = files[0] ?? null
  }
  showError = (files: readonly PickedFile[]): void => {
    this.rejectedFiles = files
  }
}

Type

feature

Installation

npm install @molecule/app-file-dropzone-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-filesystem @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

FileDropzoneProps

Props accepted by FileDropzone — the same props @molecule/app-file-dropzone-react accepts. The node prop (children) is projected content in Angular (an input cannot carry a node), so it is typed unknown: pass it in the host template, not as a value.

interface FileDropzoneProps {
  /** Called with the files the user selected or dropped, in selection order. */
  onFiles: (files: readonly PickedFile[]) => void
  /** Accept attribute (e.g. `'image/*'` or `'.pdf,.docx'`). */
  accept?: string
  /** Allow multi-file selection. Defaults to false. */
  multiple?: boolean
  /** Max file size in bytes. Files exceeding are rejected. */
  maxSize?: number
  /** Called with rejected files (wrong type or size). */
  onRejected?: (files: readonly PickedFile[]) => void
  /** Content rendered inside the dropzone, projected as the element's default content. */
  children?: unknown
  /** Disabled state. */
  disabled?: boolean
  /** Extra classes on the dropzone wrapper. */
  className?: string
}

Classes

FileDropzone

FileDropzone component.

Drag-drop + click-to-browse file upload zone. Pure UI — apps handle the actual upload. Rejects files exceeding maxSize or not matching accept (best-effort extension/MIME check) via onRejected.

The host IS the root <div> (div[mol-file-dropzone]), matching React's root exactly: role, tabindex, data-mol-id, the drag/click/keyboard handlers, the ClassMap classes and the inline drop-surface style live on it. children is projected content; the default copy renders only when nothing is projected.

@Component({
  selector: 'div[mol-file-dropzone]',
  standalone: true,
  hostDirectives: [MolPlacement],
  inputs: ['onFiles', 'accept', 'multiple', 'maxSize', 'onRejected', 'disabled', 'className'],
  host: {
    role: 'button',
    tabindex: '0',
    'data-mol-id': 'file-dropzone',
    '[attr.aria-disabled]': 'disabled ?? null',
    '[class]': 'classes()',
    '[style.border]': 'borderStyle()',
    '[style.border-radius]': '"12px"',
    '[style.min-height]': '"140px"',
    '[style.background]': 'dragging() ? backgroundStyle : null',
    '(dragover)': 'onDragOver($event)',
    '(dragleave)': 'onDragLeave()',
    '(drop)': 'onDrop($event)',
    '(click)': 'onClick($event)',
    '(keydown)': 'onKeyDown($event)',
  },
  // prettier-ignore
  template: `<input #fileInput type="file" [attr.accept]="accept ?? null" [attr.multiple]="multiple ? '' : null" [attr.disabled]="disabled ? '' : null" (change)="onInputChange()" style="display: none" /><span #contentSlot><ng-content></ng-content></span>@if (defaultCopyShown()) {<p [class]="dropHereClasses()">{{ dropHereText() }}</p>@if (accept) {<p [class]="acceptsClasses()">{{ acceptsText() }}</p>}}`,
})
export class FileDropzone {
  /** Called with the files the user selected or dropped, in selection order. */
  onFiles?: FileDropzoneProps['onFiles']
  /** Accept attribute (e.g. `'image/*'` or `'.pdf,.docx'`). */
  accept?: string
  /** Allow multi-file selection. Defaults to false. */
  multiple?: boolean
  /** Max file size in bytes. Files exceeding are rejected. */
  maxSize?: number
  /** Called with rejected files (wrong type or size). */
  onRejected?: FileDropzoneProps['onRejected']
  /** Disabled state. */
  disabled?: boolean
  /** Extra classes on the dropzone wrapper. */
  className?: string

  /** The hidden file input (opened by a click or Enter/Space on the zone). */
  @ViewChild('fileInput') private fileInput?: ElementRef<HTMLInputElement>
  /** The projected-content capture (its span never renders; `placeContentBefore` stands in its place). */
  @ViewChild('contentSlot', { static: true }) private contentSlot?: ElementRef<HTMLSpanElement>

  /** Shared DOM event handlers for this host and its input. */
  protected readonly handlers = createBrowserFileInput(
    () => this.fileInput?.nativeElement,
    () => ({
      accept: this.accept,
      disabled: this.disabled,
      maxSize: this.maxSize,
      multiple: this.multiple,
      onFiles: (files) => this.onFiles?.(files),
      onRejected: this.onRejected,
    }),
    fromBrowserFile,
  )

  /** The i18n handle (locale-reactive), read in an injection context. */
  private readonly i18n = useTranslation()
  /** Whether a drag is over the zone (React's `useState`). */
  private readonly dragging = signal(false)
  /** Whether the default copy renders (React's `children ?? default`). */
  readonly defaultCopyShown = signal(true)

  /**
   * Renders the projected content in the capture's place and withdraws the
   * capture, then shows the default copy only while nothing is projected, as
   * React's `children ?? default` does — re-decided whenever the content
   * changes (children taken away and given back included).
   */
  constructor() {
    usePlacement((hasContent) => {
      const slot = this.contentSlot?.nativeElement
      placeContentBefore(slot, slot)
      setElementPresent(slot, false)
      this.defaultCopyShown.set(!(slot ? hasContent(slot) : false))
    })
  }

  /** The drag-over fill, a theme token mixed into transparency. */
  readonly backgroundStyle = 'color-mix(in srgb, var(--mol-color-primary, #3366ff) 6%, transparent)'

  /**
   * The current class map.
   * @returns The UIClassMap.
   */
  cm(): UIClassMap {
    return getClassMap()
  }

  /**
   * The wrapper class list (React's `cm.cn(cm.flex({…}), cm.sp('p', 6),
   * cm.textCenter, !disabled ? cm.cursorPointer : undefined, className)`).
   * @returns The class string.
   */
  classes(): string {
    return this.cm().cn(
      this.cm().flex({ direction: 'col', align: 'center', justify: 'center' }),
      this.cm().sp('p', 6),
      this.cm().textCenter,
      !this.disabled ? this.cm().cursorPointer : undefined,
      this.className,
    )
  }

  /**
   * The dashed drop-surface border (React's `border`), thick in the primary
   * colour while a drag is over the zone and muted otherwise.
   * @returns The border declaration value.
   */
  borderStyle(): string {
    return this.dragging()
      ? '2px dashed var(--mol-color-primary, #3366ff)'
      : '2px dashed var(--mol-color-border, rgba(128,128,128,0.35))'
  }

  /**
   * The default "drop here" paragraph's class (React's
   * `cm.cn(cm.textSize('sm'), cm.fontWeight('semibold'))`).
   * @returns The class string.
   */
  dropHereClasses(): string {
    return this.cm().cn(this.cm().textSize('sm'), this.cm().fontWeight('semibold'))
  }

  /**
   * The accept-hint paragraph's class (React's
   * `cm.cn(cm.textSize('xs'), cm.sp('mt', 1))`).
   * @returns The class string.
   */
  acceptsClasses(): string {
    return this.cm().cn(this.cm().textSize('xs'), this.cm().sp('mt', 1))
  }

  /**
   * The default copy's first line (React's `fileDropzone.dropHere`).
   * @returns The translated text.
   */
  dropHereText(): string {
    return this.i18n.t(
      'fileDropzone.dropHere',
      {},
      { defaultValue: 'Drop files here or click to browse' },
    )
  }

  /**
   * The accept hint (React's `fileDropzone.accepts`). The text only renders
   * while `accept` is set (the template's `@if`), so `''` never shows.
   * @returns The translated text.
   */
  acceptsText(): string {
    return this.i18n.t(
      'fileDropzone.accepts',
      { accept: this.accept ?? '' },
      { defaultValue: 'Accepts: {{accept}}' },
    )
  }

  /** Opens the file dialog through the hidden input. */
  openDialog(): void {
    this.onClick()
  }

  /**
   * React's `onDragOver`: prevents the browser's default (which would open the
   * dropped file) and highlights the zone, unless disabled.
   *
   * @param event - The native drag event.
   */
  onDragOver(event: DragEvent): void {
    if (this.handlers.onDragOver(event)) this.dragging.set(true)
  }

  /** React's `onDragLeave`: clears the highlight. */
  onDragLeave(): void {
    this.dragging.set(false)
  }

  /**
   * React's `onDrop`: always prevents the browser's default, clears the
   * highlight, and dispatches the dropped files unless disabled.
   *
   * @param event - The native drop event.
   */
  onDrop(event: DragEvent): void {
    this.dragging.set(false)
    this.handlers.onDrop(event)
  }

  /**
   * Opens the file dialog unless the click came from the input.
   *
   * @param event - The native click, when called by the host.
   */
  onClick(event?: MouseEvent): void {
    this.handlers.onClick(event ?? { target: null, defaultPrevented: false })
  }

  /**
   * Opens the file dialog on Enter or Space.
   *
   * @param event - The native keyboard event.
   */
  onKeyDown(event: KeyboardEvent): void {
    this.handlers.onKeyDown(event)
  }

  /** Delivers the input's files after clearing it for the next selection. */
  onInputChange(): void {
    this.handlers.onChange()
  }
}

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.13.0 || ^4.0.0
  • @molecule/app-filesystem ^1.1.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common
  • @angular/core
  • @angular/platform-browser
  • @molecule/app-angular
  • @molecule/app-filesystem
  • @molecule/app-ui
  • @molecule/app-ui-angular

With multiple false (the default) only the FIRST accepted file is delivered to onFiles, even when the user drops several at once.

The accept filter is a best-effort client-side check (file extension or MIME prefix match) — treat it as UX sugar and always re-validate on the server. Files failing accept or maxSize go to onRejected (both rejection causes arrive in the same callback).

children is projected content (Angular cannot carry a node in an input): put it between the element's tags to replace the default "Drop files here or click to browse" copy, which translates via @molecule/app-locales-file-dropzone.

The zone is a keyboard-activatable role="button" (tabindex="0"): pressing Enter or Space opens the native file dialog, matching a click.

Translations

Translation strings are provided by @molecule/app-locales-file-dropzone.