Angular:如何在Angular中添加/删除文件?

DDD*_*DDD 3 javascript angular

在这里,我选择了多个图像并使用进行显示,*ngFor然后放置了一个删除按钮,该按钮出现在屏幕截图中,单击“删除”按钮。

这是我的UI截图

add.component.html

<button mat-raised-button (click)="fileInput.click()">Select File</button>

<input style="display: none" type="file" (change)="onFileChanged($event)" #fileInput multiple="true">

<div *ngFor="let selected of selectedFile;let index = index">
  <h3>{{selected.name}}</h3>
  <button mat-icon-button (click)="removeSelectedFile(index)">delete</button>
</div>
Run Code Online (Sandbox Code Playgroud)

add.component.ts

selectedFile: File;
ArrayOfSelectedFile = new Array<string>();

onFileChanged(event : any) {
  this.ArrayOfSelectedFile= [];
  this.selectedFile = event.target.files;
  this.ArrayOfSelectedFile.push(event.target.files);
}

removeSelectedFile(index){
  this.ArrayOfSelectedFile.splice(index,1);
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ale 6

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>
Run Code Online (Sandbox Code Playgroud)

和TS代码:

导入此:

import { Component, OnInit, Inject, ViewChild } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

在您的组件类中:

@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);
}
Run Code Online (Sandbox Code Playgroud)

如果您发现我已使用@ViewChild重置了value = '',那么已删除的文件将无法再次上传,那么您可以再次选择已删除的文件。

这是一个工作StackBlitz示例。