在* ngFor循环中输入正确的输入时遇到麻烦。当我添加带有第一个输入的图像(Certificat dimmatriculation)时,会显示一个占位符图像和一个删除按钮以重置输入(有效),但它同时显示在两个div下。
我只想将添加实际图像的输入作为目标。我有一个ViewChild,但似乎无法正常工作。
这是代码:
<div class="files">
<div class="single-file" *ngFor="let file of files">
<h5>{{file.title}}</h5>
<input type="file" name="file" id="{{file.slug}}" class="inputfile" #fileInput (change)="addFile(fileInput.files[0])" />
<label for="{{file.slug}}" *ngIf="!hasFile || isDeleted">
<img class="d-none d-xl-inline-block" src="assets/images/addImg.png" alt="">
Ajouter votre photo
<img class="d-block d-xl-none" src="assets/images/addImg_big.png" alt="">
</label>
<div class="placeholder" *ngIf="hasFile && !isDeleted">
<img [src]="imageUrl" />
</div>
<div class="deleteImg" *ngIf="hasFile && !isDeleted" (click)="deleteFile()">
<div class="btn btn-outline"><img src="assets/images/delete-x-icon.png" alt="Supprimer">Supprimer</div>
</div>
</div>
</div>
以及.ts中:
我声明了所有变量
file: File;
imageUrl: string | ArrayBuffer = '../app/assets/images/imgAdded.png';
hasFile = false;
isDeleted = false;
@ViewChild('fileInput', { static: false }) myFileInput: ElementRef;
files: any = [{
'title': 'Certificat dimmatriculation',
'slug': 'immatriculation',
'input': '#fileInput1'
}, {
'title': 'Preuve dassurance',
'slug': 'insurance',
'input': '#fileInput2'
}];
addFile(file: File) {
if (file) {
this.hasFile = !this.hasFile;
// this.fileName = file.name;
this.file = file;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = event => {
this.imageUrl = this.imageUrl;
// this.imageUrl = reader.result;
};
}
}
deleteFile() {
this.isDeleted = !this.isDeleted;
this.myFileInput.nativeElement.value = '';
}
当前您的问题是,您正在尝试通过使用组件级属性来管理各个file
属性。我建议使用文件属性存储上载的图像数据。然后,所有操作都将作用域限定为file
实例。
为了演示的目的,我简化了您的代码示例,并帮助您了解我采用了哪种方法。
我正在使用名为imageUrl
的单个文件上的属性来存储上载的图像数据URL。此属性中值的存在意味着已上传图像。删除图像后,该属性将被清除。
component.html
<div *ngFor="let file of files">
<h5>{{file.title}}</h5>
<label *ngIf="!file.imageUrl">
<input type="file" (change)="addFile(file, $event)" />
Ajouter votre photo
</label>
<ng-container *ngIf="file.imageUrl">
<img [src]="file.imageUrl" />
<button (click)="deleteFile(file)">Supprimer</button>
</ng-container>
</div>
现在所有操作都在单个file
对象上执行,并且需要传递到事件处理程序中。您也可以使用数组索引而不是对象引用。
file
实例和从输入上传的文件之间也可能存在一些混淆。如果可能,我建议将files
和file
变量重命名为其他名称,并在处理文件输入时保留file
。
component.ts
addFile(file, event) {
const uploaded = event.target.files[0];
if (!uploaded) {
return;
}
const reader = new FileReader();
reader.onload = () => {
file.imageUrl = reader.result;
};
reader.readAsDataURL(uploaded);
}
deleteFile(file) {
file.imageUrl = '';
}