# File upload

A drop zone and file picker that checks file type, size and count before files reach your form. The value is a `File[]`; uploading the files is up to your code.

- Package: [@vigdx/ui](https://www.npmjs.com/package/@vigdx/ui)
- Selectors: `vig-file-upload`
- Source: [libs/ui/src/lib/molecules/file-upload/file-upload.ts](https://github.com/bakyurekk/vigdx/blob/main/libs/ui/src/lib/molecules/file-upload/file-upload.ts)

```typescript title="Import"
import { FileUpload } from '@vigdx/ui/file-upload';
```

## Basic

Bind `[(value)]` to a `File[]` signal; empty is `[]`. Click the zone to open the file dialog or drop a file on it. `accept` uses the syntax of the native attribute and is also checked for dropped files.

```typescript title="file-upload-basic.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FileUpload } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-basic',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FileUpload],
  template: `
    <div class="max-w-md">
      <vig-file-upload
        label="Resume"
        hint="PDF or Word document."
        accept=".pdf,.doc,.docx"
        [(value)]="files"
      />
    </div>
    <p class="text-sm text-muted-foreground">
      {{ files().length ? files()[0].name : 'No file chosen.' }}
    </p>
  `,
})
export class FileUploadBasicDemo {
  protected readonly files = signal<File[]>([]);
}
```

## Multiple files and limits

`multiple` allows several files, `maxFiles` caps the total and `maxFileSize` the size of each file in bytes. Files that fail a check stay out of the value, show a message at once and are emitted through `rejected` with their reason.

```typescript title="file-upload-multiple.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FileUpload, type FileRejection } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-multiple',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FileUpload],
  template: `
    <div class="max-w-md">
      <vig-file-upload
        label="Photos"
        hint="Up to 3 images, 2 MB each."
        accept="image/*"
        [multiple]="true"
        [maxFiles]="3"
        [maxFileSize]="2 * 1024 * 1024"
        (rejected)="onRejected($event)"
        [(value)]="photos"
      />
    </div>
    <p class="text-sm text-muted-foreground" role="status">
      {{ photos().length }} accepted · last rejected: {{ lastRejected() || 'none' }}
    </p>
  `,
})
export class FileUploadMultipleDemo {
  protected readonly photos = signal<File[]>([]);
  protected readonly lastRejected = signal('');

  protected onRejected(rejections: FileRejection[]): void {
    this.lastRejected.set(rejections.map((r) => `${r.file.name} (${r.kind})`).join(', '));
  }
}
```

## Read-only, disabled and error

`readonly` lists the files without remove buttons and keeps the zone from opening; `disabled` blocks it. Errors show once the field is `touched` and `invalid`.

```typescript title="file-upload-states.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FileUpload } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-states',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FileUpload],
  template: `
    <div class="grid gap-6 sm:grid-cols-2">
      <vig-file-upload
        label="Signed contract"
        [multiple]="true"
        [value]="files"
        [readonly]="true"
      />
      <vig-file-upload label="Attachments" hint="Uploads are closed." [disabled]="true" />
      <vig-file-upload
        label="Invoice"
        [required]="true"
        [touched]="true"
        [invalid]="true"
        [errors]="[{ kind: 'required' }]"
        [errorMessages]="{ required: 'Attach the invoice to continue.' }"
      />
    </div>
  `,
})
export class FileUploadStatesDemo {
  // Sample files; real ones come from the picker or a drop.
  protected readonly files = [
    new File([new Uint8Array(248_000)], 'contract-signed.pdf', { type: 'application/pdf' }),
    new File([new Uint8Array(1_850_000)], 'appendix-a.pdf', { type: 'application/pdf' }),
  ];
}
```

## Translated labels

`dropLabel` and `removeAriaLabel` (the file name is appended) translate the texts per instance. `errorMessages` can use the `{file}`, `{maxSize}` and `{maxFiles}` placeholders of the rejection errors. File sizes are formatted for the active locale.

```typescript title="file-upload-labels.ts"
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { FileUpload } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-labels',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FileUpload],
  template: `
    <div class="max-w-md">
      <vig-file-upload
        label="Belgeler"
        dropLabel="Dosyaları buraya bırakın veya seçmek için tıklayın"
        removeAriaLabel="Kaldır"
        [multiple]="true"
        [maxFileSize]="5 * 1024 * 1024"
        [errorMessages]="{ maxFileSize: '{file} dosyası {maxSize} sınırını aşıyor.' }"
        [value]="files"
      />
    </div>
  `,
})
export class FileUploadLabelsDemo {
  protected readonly files = [
    new File([new Uint8Array(96_000)], 'kimlik.pdf', { type: 'application/pdf' }),
  ];
}
```

## Reactive Forms

Import `VigValueAccessor` next to the component to use `formControlName`, `[formControl]` or `ngModel`. Type the control as `File[]`; `Validators.required` treats `[]` as missing.

```typescript title="file-upload-reactive-forms.ts"
import { ChangeDetectionStrategy, Component, computed } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
import { Button } from '@vigdx/ui/button';
import { VigValueAccessor } from '@vigdx/ui/core';
import { FileUpload } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-reactive-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [ReactiveFormsModule, Button, FileUpload, VigValueAccessor],
  template: `
    <form class="flex flex-col gap-4" (ngSubmit)="submit()">
      <div class="max-w-md">
        <vig-file-upload label="Receipts" [multiple]="true" [formControl]="receipts" />
      </div>
      <div class="flex gap-2">
        <vig-button type="submit" label="Submit claim" />
        <vig-button label="Reset" variant="secondary" (click)="receipts.reset()" />
      </div>
      <p class="text-sm text-muted-foreground">Files: {{ names() }}</p>
    </form>
  `,
})
export class FileUploadReactiveFormsDemo {
  // Validators.required treats an empty array as missing.
  protected readonly receipts = new FormControl<File[]>([], {
    nonNullable: true,
    validators: Validators.required,
  });
  private readonly value = toSignal(this.receipts.valueChanges, {
    initialValue: this.receipts.value,
  });
  protected readonly names = computed(
    () =>
      this.value()
        .map((f) => f.name)
        .join(', ') || '[]',
  );

  protected submit(): void {
    this.receipts.markAsTouched();
  }
}
```

## Signal Forms

`vig-file-upload` implements `FormValueControl<File[]>`. Signal Forms' `required()` treats `[]` as filled, so check the length with `validate()` for a mandatory upload.

```typescript title="file-upload-signal-forms.ts"
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
import { FormField, form, validate } from '@angular/forms/signals';
import { FileUpload } from '@vigdx/ui/file-upload';

@Component({
  selector: 'app-file-upload-signal-forms',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [FormField, FileUpload],
  template: `
    <div class="max-w-md">
      <vig-file-upload
        label="Proof of address"
        accept=".pdf,image/*"
        [multiple]="true"
        [maxFiles]="2"
        [formField]="application.documents"
      />
    </div>
    <p class="text-sm text-muted-foreground">
      Valid: {{ application().valid() ? 'yes' : 'no' }} · {{ model().documents.length }} file(s)
    </p>
  `,
})
export class FileUploadSignalFormsDemo {
  protected readonly model = signal({ documents: [] as File[] });
  // required() treats [] as filled, so check the length instead.
  protected readonly application = form(this.model, (path) => {
    validate(path.documents, ({ value }) =>
      value().length ? undefined : { kind: 'required', message: 'Attach at least one document.' },
    );
  });
}
```

## Styling hooks

Internal elements carry a stable `data-part` and the component's `data-scope`; both are public API, so removing one is a breaking change. Select a part by both, e.g. `[data-scope="file-upload"][data-part="label"] { … }`: the pair stays within this component when kit components nest, and also reaches parts in overlay panels, which render outside the host. State is exposed through `aria-*` and, where listed, a `data-state`; literal values are checked by the API gate, values computed from the component's state follow its documented types. Other `data-*` attributes listed below (such as `data-opening` while an overlay animates) are API too. See [Customizing](https://vigdx.com/docs/theming.md#customizing).

Scope: `[data-scope="file-upload"]`

| Part | Element | data-state |
| --- | --- | --- |
| `label` | The visible label. |   |
| `dropzone` | The drop zone button that opens the file dialog. |   |
| `icon` | The upload icon in the drop zone. |   |
| `prompt` | The drop zone text. |   |
| `input` | The hidden native file input. |   |
| `files` | The list of chosen files. |   |
| `file` | One file row. |   |
| `file-name` | The file name (base truncates, extension stays). |   |
| `file-size` | The formatted file size. |   |
| `remove` | The remove button of a file. |   |
| `hint` | The `vig-hint` (a `display: contents` host; style its `text` part). |   |
| `disabled-reason` | The `vig-hint` with the disabled reason (`display: contents`). |   |
| `error` | The `vig-field-error` (a `display: contents` host; style its `message` part). |   |

## Accessibility

- The drop zone is a native `<button>` named by the label and the drop text (singular or plural after `multiple`), so keyboard users open the file dialog with Enter or Space; dragging is never required. A button cannot carry `aria-required`, so `required` adds a visually hidden "Required" (`requiredLabel`) to its description.
- The chosen files are a list labelled by the field label. Long names truncate before the extension, which stays visible; the full name stays in the DOM. Each file has a remove button named "Remove" plus the file name (`removeAriaLabel`).
- Hint and error are linked to the zone through `aria-describedby`; rejected files set `aria-invalid="true"` and the message names the file and the limit.
- State the accepted types, size and count in the `hint`, so users know the limits before choosing files.

## API

### FileUpload

Selector: `vig-file-upload` · Kind: component

File picker with a drop zone. The zone is a button that opens the native file dialog, so it works by keyboard; files can also be dragged onto it. Picked files are checked against `accept`, `maxFileSize` and `maxFiles`; rejected ones are left out, reported through the field error and the `rejected` output. Empty is `[]`.

#### Inputs

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `accept` | `string` | `''` | Same syntax as the native attribute: `.pdf,image/*`. Also enforced on drop. |
| `dirty` | `boolean` | `false` | — |
| `disabled` | `boolean` | `false` | — |
| `disabledReasons` | `readonly WithOptionalFieldTree<DisabledReason>[]` | `[]` | — |
| `dropLabel` | `string \| undefined` | `undefined` | Drop-zone prompt; defaults to a singular or plural label after `multiple`. |
| `errorMessages` | `Record<string, string>` | — | — |
| `errors` | `readonly ValidationError.WithOptionalFieldTree[]` | `[]` | — |
| `hidden` | `boolean` | `false` | — |
| `hint` | `string \| undefined` | `undefined` | — |
| `invalid` | `boolean` | `false` | — |
| `label` (required) | `string` | — | — |
| `maxFiles` | `number \| undefined` | `undefined` | Most files the field holds in total. |
| `maxFileSize` | `number \| undefined` | `undefined` | Largest accepted file, in bytes. |
| `multiple` | `boolean` | `false` | — |
| `name` | `string` | `''` | — |
| `pending` | `boolean` | `false` | — |
| `readonly` | `boolean` | `false` | — |
| `removeAriaLabel` | `string \| undefined` | `undefined` | — |
| `required` | `boolean` | `false` | — |
| `requiredLabel` | `string \| undefined` | `undefined` | Screen-reader text conveying `required`: the drop zone is a button, which cannot carry `aria-required`, so it joins the description. |
| `touched` | `boolean` | `false` | — |
| `value` (model) | `File[]` | `[]` | — |

#### Outputs

| Name | Payload | Description |
| --- | --- | --- |
| `rejected` | `FileRejection[]` | Files left out by the `accept`, `maxFileSize` or `maxFiles` checks. |
| `touch` | `void` | — |
| `valueChange` | `File[]` | — |

#### Methods

| Signature | Description |
| --- | --- |
| `addFiles(files: Iterable<File>): FileRejection[]` | Adds files after checking them; returns the rejected ones. |
| `browse(): void` | Opens the native file dialog. |
| `focus(options?: FocusOptions): void` | Moves focus to the control's interactive element (the input, or the trigger of a popup control). Signal Forms calls it through `field().focusBoundControl()`; the host element itself cannot take focus. |
| `remove(index: number): void` | Removes the file at `index`. |
| `reset(): void` | Returns the control to its pristine look: drops in-progress text, closes an open popup, clears errors the component raised itself and the submitted state of `errorDisplay: 'interacted'`. Signal Forms calls it from `field().reset()`; `VigValueAccessor` from `control.reset()`. It never changes the value: the bound form owns that. |

### VigValueAccessor

Kind: directive

Bridges the vigdx form fields to Reactive Forms (`formControl`, `formControlName`) and template-driven forms (`ngModel`). Import it next to the component; Signal Forms (`[formField]`) need no accessor.

#### Methods

| Signature | Description |
| --- | --- |
| `registerOnChange(fn: (value: unknown) => void): void` | — |
| `registerOnTouched(fn: () => void): void` | — |
| `setDisabledState(disabled: boolean): void` | — |
| `writeValue(value: unknown): void` | — |
