Angular:如何在Angular中添加/删除文件? [英] Angular : How to Add/Remove Files in the Angular?
问题描述
在这里我选择多个图像并使用*ngFor
进行显示,然后在其中放置了一个删除按钮,该按钮显示在屏幕快照中,单击删除"按钮我想从所选列表中删除所选图像,我尝试了以下代码,但没有适当的解决方案.
Here i choose multiple images and shows using *ngFor
And there I have placed a delete button which is appear in the screenshot, click on delete button i want to delete chosen image from chosen list i tried below code but i not getting proper solution.
add.component.html
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>
add.component.ts
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);
}
推荐答案
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 = ''
而发现已删除的文件无法再次上传,则可以再次选择已删除的文件.
If you notice that the Deleted file is not available for upload again for that I have used @ViewChild
to reset the value = ''
, then you can select the deleted file again.
这是一个有效的 StackBlitz
示例.
Here is a working StackBlitz
example.
这篇关于Angular:如何在Angular中添加/删除文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!