Angular : How to Add/Remove Files in the Angular?

前端 未结 5 1521
旧巷少年郎
旧巷少年郎 2021-01-18 10:11

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

5条回答
  •  悲&欢浪女
    2021-01-18 10:30

    HTML Code:

    
    
    
    
    

    {{selected}}

    And TS code:

    Import this:

    import { Component, OnInit, Inject, ViewChild } from '@angular/core';
    

    And Inside your component class:

    @ViewChild('attachments') attachment: any;
    
    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);
    }
    

    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.

    Here is a working StackBlitz example.

提交回复
热议问题