HTML-код:
<button mat-raised-button (click)="fileInput.click()">Select File</button>
<input style="display: none" #attachments type="file" (change)="onFileChanged($event)" #fileInput multiple="true">
<div *ngFor="let selected of listOfFiles;let index = index">
<h3>{{selected}}</h3>
<button mat-icon-button (click)="removeSelectedFile(index)">delete</button>
</div>
И код TS:
Импортируйте это:
import { Component, OnInit, Inject, ViewChild } from '@angular/core';
И внутри класса вашего компонента:
@ViewChild('attachments') attachment: any;
selectedFile: File;
fileList: File[] = [];
listOfFiles: any[] = [];
onFileChanged(event: any) {
for (var i = 0; i <= event.target.files.length - 1; i++) {
var selectedFile = event.target.files[i];
this.fileList.push(selectedFile);
this.listOfFiles.push(selectedFile.name)
}
this.attachment.nativeElement.value = '';
}
removeSelectedFile(index) {
// Delete the item from fileNames list
this.listOfFiles.splice(index, 1);
// delete file from FileList
this.fileList.splice(index, 1);
}
Если вы заметили, что удаленный файл снова недоступен для загрузки, для этого я использовал @ViewChild
для сброса value = ''
, то вы можете снова выбрать удаленный файл.
Вот рабочий StackBlitz
пример.