[英]Angular 8 ngFor - how to get row ID
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:我想上传文件并在特定行中显示文件名,但每次上传文件时,无论 div 行如何,我的方法都会得到 index = 0:
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.对于您的更新和评论,还要注意您的
browseFile
函数,问题在于:您通过 id 获取文件,但所有文件都具有相同的 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.事实上,通过这些更改,您可以去掉
uploadFile
函数中的index
参数。
Your *ngFor
is wrong.你的
*ngFor
是错误的。 You have to adapt your index
at the end:你必须在最后调整你的
index
:
<div class="row" *ngFor="let evidence of evidences; let i = index">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.