Skip to content

Instantly share code, notes, and snippets.

@naumanahmed19
Created October 13, 2017 17:32
Show Gist options
  • Save naumanahmed19/2f6a7f4f1234fd912439a38afe6dfac3 to your computer and use it in GitHub Desktop.
Save naumanahmed19/2f6a7f4f1234fd912439a38afe6dfac3 to your computer and use it in GitHub Desktop.
Angular4 Form Data service to get all inputs fields and uploaded files at once
import { Injectable } from '@angular/core';
@Injectable()
export class FormDataService {
constructor() { }
formData(formGroup, fileInput:any='',fileInputName:string = 'file') {
let formData = new FormData();
if(fileInput){
let fileElement = fileInput.nativeElement;
if (fileElement.files) {
for (let [key, value] of Object.entries(fileElement.files)) {
if(fileElement.files[key])
formData.append(fileInputName+key, fileElement.files[key]);
}
}
}
for (let [key, value] of Object.entries(formGroup)) {
formData.append(key, value);
}
return formData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment