I have a component that upload multiple files and this component is repeated on the same page. I want to get all formdata into to the single formdata. How can I do this?
Component HTML
<input type="file" (change)="fileSelect($event, docType)"/>
<input type="file" (change)="fileSelect($event, docType)"/>
<input type="file" (change)="fileSelect($event, docType)"/>
Component TS
formData = new FormData();
fileSelect(evt, type) {
this.formData.append('doc', <File>event.target.files[0], type);
}
Component Include in parent.html
<div class="block-1">
<app-file-upload></app-file-upload>
</div>
<div class="block-2">
<app-file-upload></app-file-upload>
</div>
<div class="block-3">
<app-file-upload></app-file-upload>
</div>
<button (click)="sendAll()">Send All Files</button>
When upload files separately, created formData only applied to the relevant component (own scope). How can I collect all formData into the single formData when click the send button.
In parent component we can query list of child components through @ViewChildren()
decoration.
@ViewChildren(AppFileUploadComponent)
fileUploadComponents: QueryList<AppFileUploadComponent>;
After in the sendAll()
method we can iterate over the child components and can get the formData
property from the AppFileUploadComponent
instance and then can store to final FormData
.
sendAll() {
let finalFormData = new FormData();
this.fileUploadComponents.forEach((component) => {
let formData = component.formData;
formData.forEach((value, key) => {
finalFormData.append(key, value);
})
});
// final form Data
console.log(finalFormData)
}
The complete code is available in stackblitz.