I am facing difficulties in targeting the correct input within a *ngFor loop. When I include an image with the first input (Certificat dimmatriculation), it displays a placeholder image and a delete button to reset the input, but it appears under both divs.
I specifically want to target only the input where the actual image is added. Despite having ViewChild, I am unable to make it function as intended.
Here is the code snippet:
<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>
Furthermore, in the .ts file:
I have declared all necessary variables
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 = '';
}