Skip to main content
The InputFile class creates a file upload input field with support for file type restrictions, size limits, drag-and-drop functionality, and comprehensive status tracking. It extends InputBaseNode and provides a rich file upload experience.

Inheritance

ObjectBase → NodeBase → InputBaseNode → InputFile

Constructor

new InputFile(
  id: string,
  placeholder?: string,
  value?: any,
  accept?: string[],
  singleLine?: boolean,
  icon?: string,
  errorMessage?: string,
  disabled?: boolean,
  validator?: Validator,
  asyncValidator?: AsyncValidator,
  action?: Action | Action[]
)

Parameters

id
string
required
The unique identifier for the file input field in the DOM.
placeholder
string
The placeholder text displayed in the file input.
value
any
The initial value (typically a File object or file path).
accept
string[]
Array of allowed file extensions (without the dot). Example: ['pdf', 'jpg', 'png']
singleLine
boolean
default:"false"
Whether the input should be displayed in a single line layout.
icon
string
Material icon name to display alongside the input.
errorMessage
string
Custom error message to display when validation fails.
disabled
boolean
Whether the file input is disabled.
validator
Validator
Synchronous validator(s) to apply to the input. Can be a single ValidatorFn, an array of ValidatorFn, or null.
asyncValidator
AsyncValidator
Asynchronous validator(s) to apply to the input. Can be a single AsyncValidatorFn, an array of AsyncValidatorFn, or null.
action
Action | Action[]
Action(s) to execute when specific events occur on the input.

Properties

PropertyTypeDescription
idstringThe unique identifier for the file input
placeholderstringThe placeholder text
typeNodeTypeThe type of node (set to 'file')
valueanyThe current file value
acceptstring[]Allowed file extensions
filenamestringDefault filename for the uploaded file
maxSizenumberMaximum file size in megabytes (MB)
dragLabelstringText displayed in the drag-and-drop area
downloadHintstringHint text for the download action
removeHintstringHint text for the remove action
retryHintstringHint text for the retry action
onStatusChange(value: FileChange) => voidCallback function triggered when file status changes
readOnlybooleanWhether the input is read-only
singleLinebooleanSingle line layout flag
iconstringMaterial icon name
errorMessagestringCustom error message
disabledbooleanDisabled state
validatorValidator | AbstractControlOptionsSynchronous validators
asyncValidatorAsyncValidatorFnAsynchronous validator
actionAction | Action[]Associated actions
hintstringHint text displayed below the input

Methods

executeStatusChange()

Executes the onStatusChange callback with the provided file change information.
executeStatusChange(value: FileChange): void
Parameters:
  • value - A FileChange object containing file status information

apply()

Inherited from ObjectBase. Applies additional properties to the node instance.
apply(options: Partial<InputFile>): this

getNativeElement()

Returns the native DOM element for this input.
getNativeElement(): HTMLElement | null

FileChange Interface

The onStatusChange callback receives a FileChange object with the following structure:
interface FileChange {
  status: 'selected' | 'invalid' | 'removed' | 'downloaded';
  file?: File;
  error?: string;
}

Usage Examples

Basic File Upload

import { InputFile } from 'mat-dynamic-form';
import { Validators } from '@angular/forms';

const documentUpload = new InputFile('document', 'Upload Document').apply({
  icon: 'upload_file',
  validator: Validators.required
});

Image Upload with Type Restrictions

const profilePicture = new InputFile('profilePicture', 'Profile Picture').apply({
  accept: ['png', 'jpg', 'jpeg', 'gif'],
  maxSize: 5, // 5 MB
  filename: 'ProfilePic',
  icon: 'add_photo_alternate',
  hint: 'Upload your profile picture (max 5 MB)',
  errorMessage: 'Invalid file format or size',
  dragLabel: 'Drag & drop your image here'
});

PDF Upload Only

const pdfUpload = new InputFile('pdfDocument', 'PDF Document').apply({
  accept: ['pdf'],
  maxSize: 10, // 10 MB
  filename: 'Document',
  hint: 'Upload a PDF file (max 10 MB)',
  errorMessage: 'Please upload a valid PDF file',
  dragLabel: 'Drop your PDF here',
  validator: Validators.required
});

File Upload with Status Tracking

import { FileChange } from 'mat-dynamic-form';

const fileUpload = new InputFile('attachment', 'Attachment').apply({
  accept: ['pdf', 'doc', 'docx', 'txt'],
  maxSize: 20,
  icon: 'attach_file',
  onStatusChange: (status: FileChange) => {
    console.log('File status:', status.status);
    
    switch (status.status) {
      case 'selected':
        console.log('File selected:', status.file?.name);
        console.log('File size:', status.file?.size, 'bytes');
        break;
      case 'invalid':
        console.error('Invalid file:', status.error);
        alert(`Error: ${status.error}`);
        break;
      case 'removed':
        console.log('File removed');
        break;
      case 'downloaded':
        console.log('File downloaded');
        break;
    }
  }
});

Custom Labels and Hints

const resumeUpload = new InputFile('resume', 'Resume').apply({
  accept: ['pdf', 'doc', 'docx'],
  maxSize: 5,
  filename: 'Resume',
  dragLabel: 'Drag & drop your resume here or click to browse',
  downloadHint: 'Download your resume',
  removeHint: 'Remove resume',
  retryHint: 'Try uploading again',
  hint: 'Supported formats: PDF, DOC, DOCX (max 5 MB)',
  errorMessage: 'Please upload a valid resume file'
});

Multiple File Types

const documentUpload = new InputFile('documents', 'Documents').apply({
  accept: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'],
  maxSize: 25,
  filename: 'Document',
  icon: 'folder_open',
  hint: 'Upload office documents (max 25 MB)',
  dragLabel: 'Drag & drop your document here'
});

Image Upload with Preview

const imageUpload = new InputFile('photo', 'Photo').apply({
  accept: ['png', 'jpg', 'jpeg'],
  maxSize: 10,
  icon: 'image',
  onStatusChange: (status: FileChange) => {
    if (status.status === 'selected' && status.file) {
      // Create image preview
      const reader = new FileReader();
      reader.onload = (e) => {
        const imageUrl = e.target?.result as string;
        console.log('Image preview URL:', imageUrl);
        // Display preview in UI
      };
      reader.readAsDataURL(status.file);
    }
  }
});

File Upload Form Submission

import { Component } from '@angular/core';
import { FormStructure, InputFile, Button } from 'mat-dynamic-form';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-file-upload',
  templateUrl: './file-upload.component.html'
})
export class FileUploadComponent {
  formStructure: FormStructure;

  constructor(private http: HttpClient) {
    this.formStructure = new FormStructure();
    this.formStructure.nodes = [
      new InputFile('document', 'Upload File').apply({
        accept: ['pdf', 'doc', 'docx'],
        maxSize: 10,
        validator: Validators.required
      })
    ];
    
    this.formStructure.validateActions = [
      new Button('submit', 'Upload', {
        onEvent: (param) => {
          const formValue = param.structure?.getValue();
          this.uploadFile(formValue.document);
        },
        style: 'primary'
      }).apply({
        validateForm: true,
        icon: 'cloud_upload'
      })
    ];
  }

  uploadFile(file: File) {
    const formData = new FormData();
    formData.append('file', file);
    
    this.http.post('/api/upload', formData).subscribe(
      response => console.log('Upload successful:', response),
      error => console.error('Upload failed:', error)
    );
  }
}

Conditional File Upload

import { RadioGroup, OptionChild, InputFile } from 'mat-dynamic-form';

const documentTypeSelector = new RadioGroup('docType', 'Document Type', [
  new OptionChild('Passport', 'passport'),
  new OptionChild('ID Card', 'id_card'),
  new OptionChild('Driver License', 'license')
]).apply({
  action: {
    type: 'valueChange',
    onEvent: (param) => {
      const acceptTypes = param.event === 'passport' 
        ? ['pdf'] 
        : ['png', 'jpg', 'jpeg'];
      
      const uploadField = new InputFile('documentUpload', 'Upload Document').apply({
        accept: acceptTypes,
        maxSize: 10,
        hint: `Upload your ${param.event === 'passport' ? 'passport PDF' : 'ID image'}`
      });
      
      // Update or add the upload field
      param.structure.createNodes(1, [uploadField]);
    }
  }
});

Common File Type Groups

Images

accept: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg']

Documents

accept: ['pdf', 'doc', 'docx', 'txt', 'rtf']

Spreadsheets

accept: ['xls', 'xlsx', 'csv']

Presentations

accept: ['ppt', 'pptx', 'key']

Archives

accept: ['zip', 'rar', '7z', 'tar', 'gz']

Media

accept: ['mp4', 'avi', 'mov', 'mp3', 'wav', 'flac']

Best Practices

  1. File Type Restrictions: Always specify accept to limit file types
  2. Size Limits: Set appropriate maxSize to prevent large file uploads
  3. Clear Messaging: Use hint and dragLabel to guide users
  4. Error Handling: Provide clear errorMessage for validation failures
  5. Status Tracking: Implement onStatusChange for user feedback
  6. Security: Validate file types and sizes on the backend as well
  7. Accessibility: Ensure the file input is keyboard accessible
  8. Mobile Support: Test drag-and-drop alternatives on mobile devices

Build docs developers (and LLMs) love