All Projects → jwelker110 → file-input-accessor

jwelker110 / file-input-accessor

Licence: other
Angular directive that provides file input functionality in Angular forms.

Programming Languages

typescript
32286 projects
HTML
75241 projects
javascript
184084 projects - #8 most used programming language
SCSS
7915 projects

Projects that are alternatives of or similar to file-input-accessor

Angular File Uploader
Angular file uploader is an Angular 2/4/5/6/7/8/9/10 + file uploader module with Real-Time Progress Bar, Responsive design, Angular Universal Compatibility, localization and multiple themes which includes Drag and Drop and much more.
Stars: ✭ 92 (+187.5%)
Mutual labels:  file, angular4, angular5, angular6
Ng2 Pdfjs Viewer
An angular 8 component for PDFJS and ViewerJS (Supports angular 2/4/5/6/7)
Stars: ✭ 150 (+368.75%)
Mutual labels:  angular4, angular5, angular6
Learn Angular From Scratch Step By Step
Angular step by step tutorial covering from basic concepts of Angular Framework to building a complete Angular app using Angular Material components. We will go through the main building blocks of an Angular 7 application as well as the best practices for building a complete app with Angular.
Stars: ✭ 140 (+337.5%)
Mutual labels:  angular4, angular5, angular6
Ngx Daterangepicker Material
Pure Angular 2+ date range picker with material design theme, a demo here:
Stars: ✭ 169 (+428.13%)
Mutual labels:  angular4, angular5, angular6
Ng2 Flatpickr
Angular 2+ wrapper for flatpickr (https://github.com/chmln/flatpickr)
Stars: ✭ 91 (+184.38%)
Mutual labels:  angular4, angular5, angular6
Aspnetcore Angular Universal
ASP.NET Core & Angular Universal advanced starter - PWA w/ server-side rendering for SEO, Bootstrap, i18n internationalization, TypeScript, unit testing, WebAPI REST setup, SignalR, Swagger docs, and more! By @TrilonIO
Stars: ✭ 1,455 (+4446.88%)
Mutual labels:  angular4, angular5, angular6
Sb Admin Bs4 Angular 8
Simple Dashboard Admin App built using Angular 8 and Bootstrap 4
Stars: ✭ 1,931 (+5934.38%)
Mutual labels:  angular4, angular5, angular6
Angular Froala Wysiwyg
Angular 4, 5, 6, 7, 8 and 9 plugin for Froala WYSIWYG HTML Rich Text Editor.
Stars: ✭ 696 (+2075%)
Mutual labels:  angular4, angular5, angular6
Ng Select
⭐ Native angular select component
Stars: ✭ 2,781 (+8590.63%)
Mutual labels:  angular4, angular5, angular6
Ng2 Idle
Responding to idle users in Angular (not AngularJS) applications.
Stars: ✭ 240 (+650%)
Mutual labels:  angular4, angular5, angular6
AuthGuard
Example repo for guarding routes post
Stars: ✭ 42 (+31.25%)
Mutual labels:  angular4, angular5, angular6
Springbootangularhtml5
♨️ Spring Boot 2 + Angular 11 + HTML5 router mode + HTTP interceptor + Lazy loaded modules
Stars: ✭ 89 (+178.13%)
Mutual labels:  angular4, angular5, angular6
Ngx Papaparse
Papa Parse wrapper for Angular
Stars: ✭ 83 (+159.38%)
Mutual labels:  angular4, angular5, angular6
Ng Simple Slideshow
A simple, responsive slideshow for Angular 4+.
Stars: ✭ 119 (+271.88%)
Mutual labels:  angular4, angular5, angular6
Nebular
💥 Customizable Angular UI Library based on Eva Design System 🌚✨Dark Mode
Stars: ✭ 7,368 (+22925%)
Mutual labels:  angular4, angular5, angular6
Popover
Angular CDK Popover, no default style, examples using @angular/material
Stars: ✭ 156 (+387.5%)
Mutual labels:  angular4, angular5, angular6
Ngx Monaco Editor
Monaco Editor component for Angular 2 and Above
Stars: ✭ 347 (+984.38%)
Mutual labels:  angular4, angular5, angular6
Angular Material App
基于最新Angular 9框架与Material 2技术的web中后台前端应用框架。
Stars: ✭ 509 (+1490.63%)
Mutual labels:  angular4, angular5, angular6
Angular5 Seed
Angular5 Seed for Application
Stars: ✭ 222 (+593.75%)
Mutual labels:  angular4, angular5, angular6
PHP-FileUpload
Simple and convenient file uploads — secure by default
Stars: ✭ 53 (+65.63%)
Mutual labels:  input, file, form

Looking for the changelog?

(Versions of this package < 2.0.1) If you see an error about an unknown token { with some imports.

This isn't compatible with Angular Universal (Server side rendering) yet. I'll fix this in a future release. Until then, if you need to server-side render this package, please refer to the instructions here. Summarized below:

  • npm i --save-dev babel-cli babel-preset-es2015
  • create a .babelrc file in the project's root directory with the following contents:
    {
        "presets": ["es2015"]
    }
  • Add a script to your package.json:
    "compile:file-input-accessor": "babel node_modules/file-input-accessor -d node_modules/file-input-accessor --presets es2015"
  • Add a postinstall script to your package.json scripts section:
    "postinstall": "compile:file-input-accessor"

FileInputAccessor

Adds Reactive and Template behavior you're used to using with Angular Forms, but for <input type="file">. Check out the demo to see it in action.

Sample code for sending the files from Angular to your backend is further down this page.

Provides NG_VALUE_ACCESSOR implementing the ControlValueAccessor interface. For more info, refer to this stack overflow answer linked on this issue.

Which version should I use?

Version 1.x.x uses Rxjs v5.5.x. Rxjs v6 underwent some changes that include adjustments to the way operators are imported along with other breaking changes.

Version 2.x.x uses Rxjs v6. If you're interested in updating your projects, a package has been created for that very purpose by the Rxjs team.

As a general rule:

  • For Angular 4 and 5, use version 1.x.x.
  • For Angular 6 use version 2.x.x.
  • Angular 7 and above aligns with the Angular version, so for Angular 7, use 7.x.x, Angular 8, use 8.x.x, etc..

RxJS

RxJS docs (beta as of 2018/05/05). Another very helpful resource to familiarize yourself with Rxjs by providing a list of commonly used operators with examples.

Using with your forms

  1. Install package from npm

    npm i file-input-accessor

  2. Import the FileInputAccessorModule.

     import {BrowserModule} from '@angular/platform-browser';
     import {FileInputAccessorModule} from "file-input-accessor";
    
     @NgModule({
         declarations: [
             AppComponent
         ],
         imports: [
             BrowserModule,
             FileInputAccessorModule
         ],
         providers: [],
         bootstrap: [AppComponent]
     })
     export class AppModule {}
  3. That's it. You can use FormControl and NgModel with your file input.

     <!--file-upload.component.html-->
    
     <form>
       <!--Reactive form control-->
       <input type="file" multiple [formControl]="fileControl">
     </form>
    
     <form>
       <!--Template form control, using model changes to trigger upload-->
       <input type="file" multiple name="templateFileUploadControl" [ngModel]="modelChangesFiles" (ngModelChange)="onFileInputChange($event)">
     </form>
    
     <form>
       <!--Template form control, upload is manually triggered-->
       <input type="file" multiple [(ngModel)]="manualChangesFiles" name="templateFileUploadControl2">
       <button type="button" (click)="submitFiles()">Click to upload</button>
     </form>
    

Uploading the files

  1. Import the HttpClientModule if it isn't already.

     @NgModule({
         declarations: [
             AppComponent,
             FileUploadComponent
         ],
         imports: [
             BrowserModule,
             RouterModule.forRoot(ROUTES),
             HttpClientModule,
             FileInputAccessorModule
         ],
         providers: [],
         bootstrap: [AppComponent]
     })
     export class AppModule {
     }
  2. When you're ready to upload your files, append them to your FormData and use HttpClient to call your file upload endpoint.

     @Component({
         selector: 'app-file-upload',
         templateUrl: './file-upload.component.html',
         styleUrls: ['./file-upload.component.css']
     })
     export class FileUploadComponent implements OnInit {
    
         fileControl = new FormControl();
    
         modelChangesFiles: ICustomFile[] = [];
         manualChangesFiles: ICustomFile[] = [];
    
         constructor(private _http: HttpClient) {
         }
    
         /**
          * Subscribe to the valueChanges Observable on the reactive FormControl.
          */
         ngOnInit() {
             this.fileControl.valueChanges
                 .pipe(mergeMap(files => this.uploadFiles(files)))
                 .subscribe(() => this.fileControl.setValue([]));
         }
    
         /**
          * (ngModelChange) event handler
          *
          * @param {ICustomFile[]} event
          */
         onFileInputChange(event: ICustomFile[]) {
             this.uploadFiles(event)
                 .subscribe(() => (this.modelChangesFiles = []));
         }
    
         /**
          * Upload button's (click) event handler
          */
         submitFiles() {
             this.uploadFiles(this.manualChangesFiles)
                 .subscribe(() => (this.manualChangesFiles = []));
         }
    
         /**
          * Appends the provided files to FormData and returns an Observable that will pass the FormData
          * to the api when subscribed.
          *
          * @param {ICustomFile[]} files
          * @returns {Observable<Object>}
          */
         private uploadFiles(files: ICustomFile[]): Observable<Object> {
             if (!files || files.length === 0) {
                 return EMPTY;
             }
    
             const data = new FormData();
    
             for (const file of files) {
                 data.append('file', file.slice(), file.name);
             }
             return this._http.post('/api/files', data);
         }
     }

Validation

An async validator is included and only runs if sync validation passes and values are provided to the accessor inputs. The following errors may be set true on the control if at least one file fails validation:

  • fileSize - File size is too large.
  • fileType - File type failed to match.
  • fileExt - File extension failed to match.
  • The image validation requires withMeta set to true.
    • imageWidth - Image does not meet width requirement.
    • imageHeight - Image does not meet height requirement.
    • (>= 8.1.0) maxHeight - Image is too tall.
    • (>= 8.1.0) maxWidth - Image is too wide.
    • (>= 8.1.0) minHeight - Image is not tall enough.
    • (>= 8.1.0) minWidth - Image is not wide enough

Accessor Inputs

All inputs are optional.

  • [allowedExt] - Used to validate each file's extension. Accepts the following:
    • A RegExp instance.
    • A String that will be used to create a new RegExp.
    • An array of strings that will be joined into a single capture group and used to create a new RegExp.
  • [allowedTypes] - Accepts the same as allowedExt but will be used to validate the file's type.
  • [size] - Used to verify each file's size (bytes) is <= the provided value.
  • [withMeta] - If true, each file will receive additional properties adhering to the ICustomFile interface. If you plan to validate maxHeight and maxWidth, true is required.
  • [maxHeight] - The largest acceptable height, in pixels, for image files.
  • [maxWidth] - The largest acceptable width, in pixels, for image files.
  • [minHeight] - The smallest acceptable height, in pixels, for image files.
  • [minWidth] - The smallest acceptable width, in pixels, for image files.

ICustomFile

An interface implemented by the Files added to the control. All properties are optional and only present if withMeta input is set to true.

  • If the file's type is image:
    • imgSrc - Contains a data: URL representing the file data.
    • imgHeight - The height of the image, in pixels.
    • imgWidth - The width of the image, in pixels.
    • isImg - true.
  • If the file's type is text:
    • textContent - The text content of the file.
  • Each file contains an errors property that contains an errors object. The following errors will be set true if the file has failed that validation check.
    • fileSize - File size is too large.
    • fileType - File type failed to match.
    • fileExt - File extension failed to match.
    • imageWidth - Image does not meet width requirement.
    • imageHeight - Image does not meet height requirement.
    • (>= 8.1.0) maxHeight - Image is too tall.
    • (>= 8.1.0) maxWidth - Image is too wide.
    • (>= 8.1.0) minHeight - Image is not tall enough.
    • (>= 8.1.0) minWidth - Image is not wide enough.
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].