Onclick,选择多个文件后从列表中删除文件

时间:2019-07-02 06:27:04

标签: angular typescript

在我的项目中,我选择了多个fileInput,然后迭代ngFor循环以显示所选文件的名称。每个名称都有一个删除按钮,用于在上传之前从列表中删除文件。我的问题与下面的代码有关,我可以从列表中隐藏选定的文件名,但是在单击“上传”时,该隐藏的文件也会被上传。我无法从列表中删除所选文件。

HTML组件代码。

<form [formGroup] = "uploadForm" (ngSubmit)="uploadFiles()">
<div class="custom_modal pb-3">
    <div class="modal-header border-0 p-1 pl-3 pr-3 d-flex justify-content-between align-items-center">
      <h3 class="m-0">Project: {{assetDetails.name}}</h3>
      <button type="button" class="close" data-dismiss="modal" (click)="closeModal()">&times;</button>
    </div>
    <div class="modal-body p-3">
      <div class="body_top d-flex justify-content-between mb-4 mt-2 align-items-center">
        <h3 class="title m-0">Add Assets</h3>
        <button class="btn btn-primary" (click)="showAllAsset();">Show All Assets</button>
      </div>

        <div class="screen_row">
          <div class="row">
              <div class="col-md-5">
                  <label class="mb-1">File Upload</label>
                  <div class="box__input">
                    //File selection from here
                    <input type="file" name="file" id="file" class="box__file" data-multiple-caption="{count} files selected" multiple  #file (change)="onFilesAdded($event)"> 
                    <label for="file">
                      <i class="fa fa-cloud-upload" aria-hidden="true"></i>
                      <span>Click or Drag file to Upload</span>
                    </label>
                  </div>
              </div>
              <div class="col-md-7">
                  <div class="inner_body">
                    <div class="row mb-2" formArrayName="fileArray" *ngFor="let file of files; let i = index">
                      <div class="col-md-12 d-flex align-items-center justify-content-between" #filename>
                        <label >{{file.name}}</label>
                        <button type="button" class="close" (click)="removeAsset(filename,i);">&times;</button>
                      </div>
                       <div class="col-md-12 pl-0 pl-sm-3">
                      </div>
                     <mat-progress-bar *ngIf="progress" mode="determinate" [value]="progress[file.name].progress | async"></mat-progress-bar>
                  </div>
              </div>
          </div>
        </div>
   </div>
    <div class="modal-footer border-0">
        <button type="submit" class="btn-primary" data-dismiss="modal">Apply</button>
        <button type="button" class="btn-primary cancle" data-dismiss="modal" (click)="closeModal()">Cancel</button>
    </div>
  </div>
</form>

Component.ts文件

export class AssetmodalComponent implements OnInit {
  @Input() assetDetails;

  @ViewChild('file', { read: false, static: false }) file;
  myInputVariable: ElementRef;
  progress;
  canBeClosed = true;
  primaryButtonText = 'Upload';
  modelReference: any;
  fileToUpload: any;
  progressvalue: any;
  showCancelButton = true;
  uploading = false;
  uploadSuccessful = false;
  uploadForm: FormGroup;
  fileput: any;
  arrayItems: {
    file: any
  }[];
  filesarray: any = [];
  public files: Set<File> = new Set();


  constructor(
    private activeModal: NgbActiveModal,
    private uploadService: FileuploadService,
    private formBuilder: FormBuilder,
    private modelService: NgbModal,
    private pageService: PagesService,
    private formbuilder: FormBuilder,
    private spinner: SpinnerVisibilityService,
    private messageservice: LoaderService,
    private utiService: UtilService,
  ) {

   }

  ngOnInit() {
    this.uploadForm = this.formBuilder.group({
      fileArray: this.formbuilder.array([])
     });
    this.arrayItems = [];
  }

  closeModal() {
    this.activeModal.close();
  }

  //onfile selected function
  onFilesAdded($event) {
    console.log('file', this.file);
    this.fileput = this.file;
    const files: { [key: string]: File  } = this.file.nativeElement.files;
    console.log(files);

   //getting files name from this loop
    for (const key in files) {
      if (!isNaN( parseInt(key, 0) )) {
        this.files.add(files[key]);
      }
     }

  }


  showAllAsset() {
  this.modelReference = this.modelService.open(ShowallassetmodalComponent,{ windowClass: 'modal_width' }) ;
}

   //on click delete button function 
  removeAsset(files,i) {
    console.log('files array', files);
    console.log('ith value', i);
    files.innerHTML = "";
}

  uploadFiles() {
    // set the component state to "uploading"
    this.messageservice.setHttpLoaderStatus(false);
    this.uploading = true;
    // start the upload and save the progress map
    this.progress = this.uploadService.upload(this.files);
    console.log('fdd0', this.progress);

    // tslint:disable-next-line: forin
    for (const key in this.progress) {
    this.progress[key].progress.subscribe(val => {

      console.log(val);
      this.progressvalue = val;
    });
    }

     // convert the progress map into an array
    const allProgressObservables = [];
     // tslint:disable-next-line: forin
    for (const key in this.progress) {
           allProgressObservables.push(this.progress[key].progress);
         }

         // Adjust the state variabless

         // The OK-button should have the text "Finish" now
    this.primaryButtonText = 'Finish';

         // The dialog should not be closed while uploading
    this.canBeClosed = false;


         // Hide the cancel-button
    this.showCancelButton = false;

         // When all progress-observables are completed...
    forkJoin(allProgressObservables).subscribe(end => {
           // ... the dialog can be closed again...
           this.canBeClosed = true;
           // ... the upload was successful...
           this.uploadSuccessful = true;
           // ... and the component is no longer uploading
           this.uploading = false;
           this.messageservice.setHttpLoaderStatus(true);
           this.activeModal.close();

         });

  }

}

所以这是我的代码。我想从onclick列表的第i个位置删除文件。请帮帮我。谢谢:)

1 个答案:

答案 0 :(得分:1)

如下更改您的removeAsset方法;

removeAsset(file: File) {
  this.files.delete(file);
}

然后在模板中,按以下方式使用它;

<div class="row mb-2" formArrayName="fileArray" *ngFor="let file of files">
  <div class="col-md-12 d-flex align-items-center justify-content-between">
    <label >{{file.name}}</label>
    <button type="button" class="close" (click)="removeAsset(file)">&times;</button>
  </div>
  <div class="col-md-12 pl-0 pl-sm-3"></div>
  <mat-progress-bar *ngIf="progress" mode="determinate" [value]="progress[file.name].progress | async"></mat-progress-bar>
</div>