I am facing an issue with uploading multiple images from different inputs. I have a form set up with a formArray to add a new input each time the "Add file" button is clicked.
this.designForm = this.fb.group({
newFiles: this.fb.array([
this.fb.control(null, Validators.required)
], Validators.required)
});
get newFiles() {
return this.designForm.get('newFiles') as FormArray;
}
addNewFiles() {
this.newFiles.push(this.fb.control(null, Validators.required));
}
The button:
<button type="button" (click)="addNewFiles()">Add new Document</button>
The input:
<div *ngFor="let newFile of newFiles.controls; let i=index">
<input type="file"
id="usecaseImage"
(change)="showPreviewImage($event)"
[formControlName]="i">
</div>
And the event method:
showPreviewImage(event: any) {
if (event.target.files && event.target.files[0]) {
var reader = new FileReader();
reader.onload = (event: any) => {
for(let i=0; i<this.newFiles.length; i++){
console.log(this.newFiles.length);
this.designForm.value.newFiles[i] = event.target.result;
}
}
reader.readAsDataURL(event.target.files[0]);
}
}
It successfully uploads the images, but when trying to preview them, it repeats the last uploaded image. For example, if I have 3 inputs with values:
input1 value-> X.JPG, input2 value-> Y.JPG and input3 value-> Z.JPG
It previews Z.JPG three times!
Edit: The preview is in another component where I retrieve data from the service:
this.designForm = this.sdlcService.designForm ;
Then I loop through the forms and their respective inputs using keyvalue pipe to extract the values.
<div *ngFor="let form of designForm ; let d = index">
<img [src]="input.value" *ngFor="let input of form | keyvalue; let s = index">
</div>
How can I resolve this issue?