My code:
<div class="row" *ngFor="let evidence of evidences, index as i">
<div class="col">
{{i}}
<input type='file' id="file" style="display:none" (change)="uploadFile(i, $event)">
<button (click)="browseFile()" style="float: left; border: none">Choose file</button>
</div>
<div class="col">
</div>
<div class="col">
<button pButton type="button" icon="pi pi-times"
class="ui-button-danger action remove" (click)="onDeleteEvidence(i)"></button>
</div>
</div>
I want to upload a file and display file name in a specific row but every time I'm uploading a file, regardless of the div row, I get index = 0 in my method:
uploadFile(index: number, event) {
console.log(index); // always 0 !!!
this.fileToUpload = event.target.files.item(0);
this.evidences[index] = {file: this.fileToUpload, publishedDate: new Date(), docTagId: 234} as IEvidence;
}
onDeleteEvidence(index: number) {
console.log(index); //works correctly!
this.evidences.splice(index, 1);
}
browseFile() {
document.getElementById('file').click();
}
fileExists(evidence: IEvidence): boolean {
return !(evidence.file === undefined || evidence.file === null);
}
What is wrong with my code?
Please, modify you template as follows:
<div class="row" *ngFor="let evidence of evidences; let i = index">
For your update and comments, pay attention also to your browseFile
function, the problem is there: you are getting your files by id, but all of your files have the same id. Try something like:
<input type='file' id="file{{i}}" style="display:none" (change)="uploadFile(i, $event)">
<button (click)="browseFile(i)" style="float: left; border: none">Choose file</button>
And:
browseFile(i) {
document.getElementById('file'+i).click();
}
In fact, with these changes you can get rid of the index
argument in your uploadFile
function.