ngx-st-file-drop
v18.0.1
Published
- [Overview](#overview) - [Installation](#installation) - [Basic Usage](#basic-usage) - [Inputs](#inputs) - [Outputs](#outputs) - [Usage Examples](#usage-examples) - [Best Practices](#best-practices)
Readme
File Drop Component - Complete Documentation
Table of Contents
Overview
The ngx-st-file-drop component is a drag-and-drop file upload component with features including:
- Drag and drop file upload
- Browse files button
- Multiple file selection support
- File validation (size and extension)
- Upload progress indicator
- Custom labels and messages
- File type restrictions
Installation
npm install ngx-st-file-dropImport the component in your module or use it as standalone:
import { NgxStFileDropComponent } from 'ngx-st-file-drop';
// In your component
imports: [NgxStFileDropComponent]Basic Usage
<ngx-st-file-drop
[multiple]="true"
[maxFileSize]="20971520"
[validAllowedExtensions]="['pdf', 'jpg', 'png']"
(onFilesUpload)="handleFilesUpload($event)"
(notValidFilesEmitter)="handleInvalidFiles($event)">
</ngx-st-file-drop>handleFilesUpload(files: File[]): void {
console.log('Valid files:', files);
// Upload files to server
}
handleInvalidFiles(files: File[]): void {
console.log('Invalid files:', files);
}Inputs
accept
- Type:
string - Default:
'*' - Description: HTML accept attribute for file input. Specifies which file types can be selected.
- Example:
[accept]="'image/*'" [accept]="'.pdf,.doc,.docx'"
multiple
- Type:
boolean - Default:
true - Description: Allows multiple file selection. Set to
falsefor single file upload. - Example:
[multiple]="false"
disabled
- Type:
boolean - Default:
false - Description: Disables the file drop component.
- Example:
[disabled]="isUploading"
showFileDropLabel
- Type:
boolean - Default:
true - Description: Shows/hides the "or drop files here" label in the drop zone.
- Example:
[showFileDropLabel]="false"
fileDropLabel
- Type:
string - Default:
'or drop files here' - Description: Custom text for the file drop label.
- Example:
fileDropLabel="Drag files here"
showBrowseBtnLabel
- Type:
boolean - Default:
true - Description: Shows/hides the browse button label text.
- Example:
[showBrowseBtnLabel]="false"
browseBtnLabel
- Type:
string - Default:
'Browse files' - Description: Custom text for the browse button.
- Example:
browseBtnLabel="Select Files"
maxFileSize
- Type:
number - Default:
undefined - Description: Maximum file size in bytes. Files larger than this will be rejected.
- Example:
[maxFileSize]="10485760" <!-- 10 MB --> [maxFileSize]="20971520" <!-- 20 MB -->
validAllowedExtensions
- Type:
string[] - Default:
[] - Description: Array of allowed file extensions (without dots). If empty, all extensions are allowed.
- Example:
[validAllowedExtensions]="['pdf', 'doc', 'docx']" [validAllowedExtensions]="['jpg', 'jpeg', 'png', 'gif']"
setUploadingLoader
- Type:
boolean - Default:
false - Description: Shows an uploading loader overlay. When set to
falseafter beingtrue, clears selected files. - Important: This input clears the selected files list when changed from
truetofalse. - Example:
[setUploadingLoader]="isUploading"
uploadingLoaderText
- Type:
string - Default:
'Uploading' - Description: Text displayed during upload when loader is active.
- Example:
uploadingLoaderText="Uploading files, please wait..."
showFileSelectedCount
- Type:
boolean - Default:
true - Description: Shows the count of selected files below the drop zone.
- Example:
[showFileSelectedCount]="false"
fileSelectedCountLabel
- Type:
string - Default:
'file(s) selected' - Description: Label text for the file count display.
- Example:
fileSelectedCountLabel="files ready to upload"
notValidFilesLabel
- Type:
string - Default:
'Invalid files: ' - Description: Label prefix for displaying invalid file names.
- Example:
notValidFilesLabel="Rejected files: "
supportedExtensionsErrorLabel
- Type:
string - Default:
'Supported extensions: ' - Description: Label for showing supported file extensions in error messages.
- Example:
supportedExtensionsErrorLabel="Allowed formats: "
Outputs
onFilesUpload
- Type:
File[] - Description: Emitted when valid files are selected or dropped. Contains array of valid File objects.
- Example:
(onFilesUpload)="handleUpload($event)" handleUpload(files: File[]): void { this.uploadService.uploadFiles(files).subscribe( response => console.log('Upload successful'), error => console.error('Upload failed') ); }
notValidFilesEmitter
- Type:
File[] - Description: Emitted when invalid files are detected (wrong extension or size). Contains array of rejected File objects.
- Example:
(notValidFilesEmitter)="handleInvalidFiles($event)" handleInvalidFiles(files: File[]): void { const fileNames = files.map(f => f.name).join(', '); this.snackbar.error(`Invalid files: ${fileNames}`); }
Usage Examples
Example 1: Basic File Upload
// Component
@Component({
selector: 'app-upload',
template: `
<ngx-st-file-drop
(onFilesUpload)="uploadFiles($event)">
</ngx-st-file-drop>
`
})
export class UploadComponent {
uploadFiles(files: File[]): void {
console.log('Uploading:', files);
}
}Example 2: Image Upload with Restrictions
// Component
@Component({
selector: 'app-image-upload',
template: `
<ngx-st-file-drop
[accept]="'image/*'"
[maxFileSize]="5242880"
[validAllowedExtensions]="imageExtensions"
fileDropLabel="Drop images here"
browseBtnLabel="Select Images"
(onFilesUpload)="uploadImages($event)"
(notValidFilesEmitter)="showError($event)">
</ngx-st-file-drop>
`
})
export class ImageUploadComponent {
imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
uploadImages(files: File[]): void {
// Upload logic
}
showError(files: File[]): void {
this.snackbar.error('Some files are invalid');
}
}Example 3: Single File Upload with Progress
// Component
@Component({
selector: 'app-single-upload',
template: `
<ngx-st-file-drop
[multiple]="false"
[setUploadingLoader]="uploading"
uploadingLoaderText="Uploading document..."
(onFilesUpload)="uploadDocument($event)">
</ngx-st-file-drop>
`
})
export class SingleUploadComponent {
uploading = false;
uploadDocument(files: File[]): void {
this.uploading = true;
this.uploadService.upload(files[0]).subscribe(
response => {
this.uploading = false;
this.snackbar.success('Upload complete');
},
error => {
this.uploading = false;
this.snackbar.error('Upload failed');
}
);
}
}Example 4: PDF Documents Only
// Component
@Component({
selector: 'app-pdf-upload',
template: `
<ngx-st-file-drop
[accept]="'.pdf'"
[validAllowedExtensions]="['pdf']"
[maxFileSize]="20971520"
fileDropLabel="Drop PDF files here"
browseBtnLabel="Browse PDF"
notValidFilesLabel="Rejected: "
supportedExtensionsErrorLabel="Only PDF files are allowed"
(onFilesUpload)="uploadPDFs($event)"
(notValidFilesEmitter)="handleRejected($event)">
</ngx-st-file-drop>
`
})
export class PDFUploadComponent {
uploadPDFs(files: File[]): void {
console.log('Valid PDFs:', files);
}
handleRejected(files: File[]): void {
console.log('Rejected files:', files);
}
}Example 5: Custom Styling and Labels
// Component
@Component({
selector: 'app-custom-upload',
template: `
<ngx-st-file-drop
[showFileDropLabel]="true"
[showBrowseBtnLabel]="true"
fileDropLabel="Drag and drop your files here"
browseBtnLabel="Choose Files"
[showFileSelectedCount]="true"
fileSelectedCountLabel="files selected"
uploadingLoaderText="Processing files..."
[setUploadingLoader]="isProcessing"
(onFilesUpload)="processFiles($event)">
</ngx-st-file-drop>
`,
styles: [`
ngx-st-file-drop {
--file-drop-border-color: #3f51b5;
--file-drop-background: #f5f5f5;
}
`]
})
export class CustomUploadComponent {
isProcessing = false;
processFiles(files: File[]): void {
this.isProcessing = true;
// Process files
setTimeout(() => {
this.isProcessing = false;
}, 2000);
}
}Example 6: Multiple File Types with Validation
// Component
@Component({
selector: 'app-document-upload',
template: `
<ngx-st-file-drop
[multiple]="true"
[maxFileSize]="maxSize"
[validAllowedExtensions]="allowedExtensions"
[disabled]="disabled"
(onFilesUpload)="uploadDocuments($event)"
(notValidFilesEmitter)="logInvalidFiles($event)">
</ngx-st-file-drop>
<div *ngIf="uploadedFiles.length > 0">
<h3>Uploaded Files:</h3>
<ul>
<li *ngFor="let file of uploadedFiles">{{ file.name }}</li>
</ul>
</div>
`
})
export class DocumentUploadComponent {
maxSize = 10485760; // 10 MB
allowedExtensions = ['pdf', 'doc', 'docx', 'txt', 'rtf'];
disabled = false;
uploadedFiles: File[] = [];
uploadDocuments(files: File[]): void {
this.uploadedFiles = [...this.uploadedFiles, ...files];
console.log('All uploaded files:', this.uploadedFiles);
}
logInvalidFiles(files: File[]): void {
files.forEach(file => {
console.log(`Invalid file: ${file.name}, Size: ${file.size}`);
});
}
}Best Practices
Set appropriate file size limits to prevent server overload:
[maxFileSize]="20971520" <!-- 20 MB -->Always specify allowed extensions for security:
[validAllowedExtensions]="['pdf', 'jpg', 'png']"Handle both success and error cases:
handleUpload(files: File[]): void { // Handle valid files } handleInvalid(files: File[]): void { // Notify user about invalid files }Use the uploading loader for better UX:
[setUploadingLoader]="isUploading"Provide clear labels that match your use case:
fileDropLabel="Drop your invoice here" browseBtnLabel="Choose Invoice"Disable the component during upload to prevent double uploads:
[disabled]="isUploading"Clear selected files by toggling the loader:
this.isUploading = true; uploadService.upload(files).subscribe( () => this.isUploading = false // This clears files );
File Validation Logic
The component validates files based on:
- File Size: If
maxFileSizeis set, files larger than this value are rejected - File Extension: If
validAllowedExtensionsis not empty, only files with matching extensions are accepted
Example validation flow:
// User drops/selects files
// Component checks each file:
// 1. Is file size <= maxFileSize? (if set)
// 2. Is file extension in validAllowedExtensions? (if set)
// Valid files -> emit via onFilesUpload
// Invalid files -> emit via notValidFilesEmitterCommon Patterns
Pattern 1: Upload with Progress
uploadFiles(files: File[]): void {
this.uploading = true;
this.uploadService.upload(files).subscribe(
response => {
this.uploading = false;
this.snackbar.success('Upload complete');
},
error => {
this.uploading = false;
this.snackbar.error('Upload failed');
}
);
}Pattern 2: Validation Feedback
handleInvalid(files: File[]): void {
const messages = files.map(f =>
`${f.name}: ${f.size > maxSize ? 'Too large' : 'Invalid type'}`
);
this.snackbar.error(messages.join(', '));
}Pattern 3: Preview Before Upload
uploadFiles(files: File[]): void {
// Show preview dialog
this.dialog.open(PreviewComponent, { data: files })
.afterClosed()
.subscribe(confirmed => {
if (confirmed) {
this.actuallyUpload(files);
}
});
}Troubleshooting
Files not clearing after upload
- Ensure you're toggling
setUploadingLoaderfromtrueback tofalse
Validation not working
- Check that
validAllowedExtensionscontains lowercase extensions without dots - Verify
maxFileSizeis in bytes, not MB
Drop zone not responding
- Make sure component is not
disabled - Check that drag events aren't being prevented by parent elements
This documentation provides complete coverage of all inputs, outputs, and usage patterns for the File Drop component.
