【问题标题】:How to reset selected file with input tag file type in Angular 2?如何在 Angular 2 中使用输入标签文件类型重置所选文件?
【发布时间】:2017-03-03 02:14:50
【问题描述】:

这是我的输入标签的样子:

<input type="file" placeholder="File Name" name="filename" (change)="onChange($event)">
<button>Reset</button>

我想在 Angular 2 中重置选定的文件。非常感谢您的帮助。如果您需要更多详细信息,请告诉我。

附言

我可以从 $event 参数中获取文件详细信息并将其保存在 typescript 变量中,但此变量未绑定到输入标记。

【问题讨论】:

  • 当你说重置时,你到底是什么意思。你能创建一个plnkr.co 并发布你面临的问题吗

标签: angular


【解决方案1】:

我通常在捕获所选文件后重置我的文件输入。无需按下按钮,您在传递给 onChange$event 对象中拥有所需的一切:

onChange(event) {
  // Get your files
  const files: FileList = event.target.files;

  // Clear the input
  event.target.value = null;
}

不同的工作流程,但 OP 没有提到按下按钮是一项要求。

*2021 年 6 月 14 日更新,将 event.srcElement 替换为 event.target,现在 srcElement 已被弃用

【讨论】:

  • 超级干净!我个人认为这应该是公认的答案。
  • srcElement 已被弃用。
  • 非常好的方法。唯一的缺点是现在允许用户一遍又一遍地选择同一个文件
  • @RodrigoBorba 您可以通过将const files 替换为this.files 之类的内容来防止这种情况发生,然后检查this.files 以查看文件是否已存在。真正取决于您在获取文件后如何处理文件
  • 你是对的。但我认为值得指出:)
【解决方案2】:

您可以使用ViewChild 访问组件中的输入。首先,您需要将#someValue 添加到您的输入中,以便您可以在组件中读取它:

<input #myInput type="file" placeholder="File Name" name="filename" (change)="onChange($event)">

然后在你的组件中你需要从@angular/core导入ViewChild

import { ViewChild } from '@angular/core';

然后你使用ViewChild 来访问来自模板的输入:

@ViewChild('myInput')
myInputVariable: ElementRef;

现在您可以使用myInputVariable 重置所选文件,因为它是对#myInput 输入的引用,例如创建方法reset() 将在您的按钮的click 事件上调用:

reset() {
    console.log(this.myInputVariable.nativeElement.files);
    this.myInputVariable.nativeElement.value = "";
    console.log(this.myInputVariable.nativeElement.files);
}

第一个console.log 将打印您选择的文件,第二个console.log 将打印一个空数组,因为this.myInputVariable.nativeElement.value = ""; 从输入中删除选定的文件。我们必须使用this.myInputVariable.nativeElement.value = ""; 来重置输入的值,因为输入的FileList 属性是只读,所以不可能只从数组中删除项目。这是工作Plunker

【讨论】:

  • 这足以清除 valuethis.myInputVariable.nativeElement.value = ""; 吗?/
  • @PardeepJain 是的,如果这是您要查找的内容,这会从文件输入中清除所选文件。
  • myInputVariable 确实是ElementRef 类型
  • 如果我有一个可变数量的“input type=file”,那么ids是动态生成的?
  • in angular 8 @ViewChild('delDocModal', {static: false})delDocModal: ElementRef;
【解决方案3】:

我正在使用一种非常简单的方法。上传文件后,我很快使用 *ngIf 删除了输入控件。这将导致输入字段从 dom 中删除并重新添加,因此它是一个新控件,因此它是 emply:

showUploader: boolean = true;

async upload($event) {
  await dosomethingwiththefile();
  this.showUploader = false;
  setTimeout(() =>{ this.showUploader = true }, 100);
}
&lt;input type="file" (change)="upload($event)" *ngIf="showUploader"&gt;

【讨论】:

    【解决方案4】:

    就我而言,我是这样做的:

     <input #fileInput hidden (change)="uploadFile($event.target.files)" type="file" />
     <button mat-button color="warn" (click)="fileInput.value=''; fileInput.click()"> Upload File</button>
    
    

    我在 HTML 中使用 #fileInput 重置它,而不是在 component.ts 中创建 ViewChild。 每当单击“上传文件”按钮时,首先它会重置#fileInput,然后触发#fileInput.click() 函数。 如果需要重置任何单独的按钮,则可以执行单击#fileInput.value=''

    【讨论】:

      【解决方案5】:

      您可以使用模板引用变量并发送到方法

      html

      <input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event, variable);">
      

      组件

      onChange(event: any, element): void {
          // codes
          element.value = '';
        }
      

      【讨论】:

      • 为我工作。我不知道为什么有人给这个解决方案点数
      【解决方案6】:

      我已将此输入标签添加到表单标签中..

       <form id="form_data">
        <input  type="file" id="file_data"  name="browse"
        (change)="handleFileInput($event, dataFile, f)"  />
      </form>
      

      我有角度的打字稿,我在下面添加了几行,在文档表单中获取您的表单 ID 并将该值设为空。

          for(let i=0; i<document.forms.length;i++){
            if(document.forms[i].length > 0){
                   if(document.forms[i][0]['value']){ //document.forms[i][0] = "file_data"
                       document.forms[i][0]['value'] = "";
                    }
            }
          }
      

      在控制台打印document.forms,你可以得到想法..

      【讨论】:

        【解决方案7】:
        <input type="file" id="image_control" (change)="validateFile($event)" accept="image/gif, image/jpeg, image/png" />
        
        validateFile(event: any): void {
            const self = this;
            if (event.target.files.length === 1) {
              event.srcElement.value = null;
            }
          }
        

        【讨论】:

        【解决方案8】:

        如果您遇到 ng2-file-upload 问题,

        HTML:

        <input type="file" name="myfile" ` **#activeFrameinputFile** `ng2FileSelect [uploader]="frameUploader" (change)="frameUploader.uploadAll()" />
        

        组件

        import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
        
        @ViewChild('`**activeFrameinputFile**`') `**InputFrameVariable**`: ElementRef;
        
        this.frameUploader.onSuccessItem = (item, response, status, headers) => {
            this.`**InputFrameVariable**`.nativeElement.value = '';
           };
        

        【讨论】:

          【解决方案9】:

          模板:

          <input [(ngModel)]="componentField" type="file" (change)="fileChange($event)" placeholder="Upload file">
          

          组件:

          fileChange(event) {
                  alert(this.torrentFileValue);
                  this.torrentFileValue = '';
              }
          }
          

          【讨论】:

            【解决方案10】:

            Angular 5

            html

            <input type="file" #inputFile>
            
            <button (click)="reset()">Reset</button>
            

            模板

            @ViewChild('inputFile') myInputVariable: ElementRef;
            
            reset() {
                this.myInputVariable.nativeElement.value = '';
            }
            

            按钮不是必需的。你可以在更改事件后重置它,它只是为了演示

            【讨论】:

            • 我使用了这个版本,它对我来说效果很好 - 谢谢@Admir
            【解决方案11】:

            我觉得很简单,使用#variable

            <input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event); variable.value='' ">
            <button>Reset</button>
            

            “variable.value = null”选项也可用

            【讨论】:

              【解决方案12】:

              短版Plunker:

              import { Component } from '@angular/core';
              
              @Component({
                selector: 'my-app',
                template: `
                    <input #myInput type="file" placeholder="File Name" name="filename">
                    <button (click)="myInput.value = ''">Reset</button>
                `
              })
              export class AppComponent {
              
              
              }
              

              我认为更常见的情况是不使用按钮而是自动重置。 Angular Template statements 支持链接表达式所以 Plunker:

              import { Component } from '@angular/core';
              
              @Component({
                selector: 'my-app',
                template: `
                    <input #myInput type="file" (change)="onChange(myInput.value, $event); myInput.value = ''" placeholder="File Name" name="filename">
                `
              })
              export class AppComponent {
              
                onChange(files, event) {
                  alert( files );
                  alert( event.target.files[0].name );
                }
              
              }
              

              还有interesting link,关于为什么值变化没有递归。

              【讨论】:

                【解决方案13】:

                实现它的一种方法是将您的输入包装在&lt;form&gt; 标签中并重置它。

                我也不考虑将表单附加到 NgFormFormControl

                @Component({
                  selector: 'form-component',
                  template: `
                    <form #form>
                      <input type="file" placeholder="File Name" name="filename">
                    </form>
                    <button (click)="reset()">Reset</button>
                `
                })
                class FormComponent {
                
                
                
                  @ViewChild('form') form;
                
                
                  reset() {
                    this.form.nativeElement.reset()
                  }
                }
                

                https://plnkr.co/edit/Ulqh2l093LV6GlQWKkUA?p=preview

                【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-03-13
                • 1970-01-01
                • 2019-05-17
                • 2020-03-31
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多