Angular 如何将同一页面上重复组件的所有formdata收集到单个formdata中?
我有一个上传多个文件的组件,这个组件在同一个页面上重复。我想把所有的formdata放到单个formdata中。我该怎么做 组件HTMLAngular 如何将同一页面上重复组件的所有formdata收集到单个formdata中?,angular,file-upload,append,form-data,Angular,File Upload,Append,Form Data,我有一个上传多个文件的组件,这个组件在同一个页面上重复。我想把所有的formdata放到单个formdata中。我该怎么做 组件HTML <input type="file" (change)="fileSelect($event, docType)"/> <input type="file" (change)="fileSelect($event, docType)"/> <input type="file" (change)="fileSelect($event
<input type="file" (change)="fileSelect($event, docType)"/>
<input type="file" (change)="fileSelect($event, docType)"/>
<input type="file" (change)="fileSelect($event, docType)"/>
组件TS
formData = new FormData();
fileSelect(evt, type) {
this.formData.append('doc', <File>event.target.files[0], type);
}
formData=newformdata();
文件选择(evt,类型){
this.formData.append('doc',event.target.files[0],type);
}
组件包含在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>
发送所有文件
单独上载文件时,创建的formData仅应用于相关组件(自己的范围)。单击“发送”按钮时,如何将所有formData收集到单个formData中。我建议您在
组件中使用@Output
装饰器。
在第一个选项中,您可以执行以下操作:
@Component(...)
export class AppFileUploadComponent{
@Output('onFileSelect')
onFileSelect: EventEmitter<any> = new EventEmitter();
...
fileSelect(evt, type) {
this.onFileSelect.emit(/* Emit the data you want*/);
// do other magical stuff here
}
}
我建议您在
组件中使用@Output
装饰器。
在第一个选项中,您可以执行以下操作:
@Component(...)
export class AppFileUploadComponent{
@Output('onFileSelect')
onFileSelect: EventEmitter<any> = new EventEmitter();
...
fileSelect(evt, type) {
this.onFileSelect.emit(/* Emit the data you want*/);
// do other magical stuff here
}
}
在父组件中,我们可以通过
@ViewChildren()
装饰查询子组件列表
@ViewChildren(AppFileUploadComponent)
fileUploadComponents: QueryList<AppFileUploadComponent>;
完整的代码可以在中找到。在父组件中,我们可以通过
@ViewChildren()
查询子组件列表
@ViewChildren(AppFileUploadComponent)
fileUploadComponents: QueryList<AppFileUploadComponent>;
完整的代码可在中找到。应使用反应式表单解决。应使用反应式表单解决
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)
}