如何在Angular 2中使用输入标签文件类型重置所选文件?


89

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

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

我想在Angular 2中重置选定的文件。非常感谢您的帮助。让我知道您是否需要更多详细信息。

聚苯乙烯

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


当您说重置时,您的意思是什么。您可以创建一个plnkr.co并发布您遇到的问题吗
abhinav

Answers:


205

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

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

然后在你的组件,你需要导入ViewChild来自@angular/core

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

然后,您可以使用ViewChild从模板访问输入:

@ViewChild('myInput')
myInputVariable: ElementRef;

现在,您可以使用myInputVariable来重置所选文件,因为它是对的输入的引用#myInput,例如reset()将在上调用的create方法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属性是readonly,所以不可能仅从数组中删除项目。这是工作中的Plunker


2
这足以清除价值this.myInputVariable.nativeElement.value = "";吗?/
Pardeep Jain's

1
@PardeepJain是的,如果您要查找的是,这将从文件输入中清除所选文件。
Stefan Svrkota'4

3
myInputVariable确实是类型ElementRef
phil294

如果我有可变数量的“输入类型=文件”怎么办,以便动态生成ID?
艾伯特·亨德里克斯

2
角度8 @ViewChild('delDocModal',{static:false})delDocModal:ElementRef;

17

角度5

html

<input type="file" #inputFile>

<button (click)="reset()">Reset</button>

模板

@ViewChild('inputFile') myInputVariable: ElementRef;

reset() {
    this.myInputVariable.nativeElement.value = '';
}

不需要按钮。您可以在更改事件后重置它,仅用于演示


我使用了这个版本,对我来说效果很好-谢谢@Admir
user1288395

15

一种实现方法是将输入内容包装在<form>标记中,然后将其重置。

我不考虑THR形式连接到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


我们可以.reset()在viewChild上使用方法吗?
Pardeep Jain

您好Edmar ...您能帮我解决这个链接上的问题吗... stackoverflow.com/questions/48769015/…–
Heena,

11

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

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

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

不同的工作流程,但OP并没有要求按下按钮...


1
超级干净!我个人认为这应该是公认的答案。
Mazen Elkashef

3

短版柱塞

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语句支持链接表达式,因此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 );
  }

}

有趣的联系,为什么没有对价值变化没有递归。


3

我认为它很简单,使用#variable

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

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


1

就我而言,我这样做如下:

 <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=''可以单击。


0

模板:

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

零件:

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

0

如果您遇到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 = '';
   };

0

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

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

我是角型打字稿,我在以下几行中添加了代码,在文档表单中获取了表单ID,并将该值设置为null。

    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,您可以了解想法。


0

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

html

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

零件

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

0

我正在使用一个非常简单的方法。上传文件后,我不久将使用* ngIf删除输入控件。这将导致从dom中删除输入字段并对其进行重新添加,因此,这是一个新控件,因此非常有用:

showUploader: boolean = true;

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


-1
<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;
    }
  }

1
您能否在代码上提供简短说明以说明其工作原理?
雅各布·尼尔森

根据MDN,这支持不佳。作为参考,请查看以下URL developer.mozilla.org/en-US/docs/Web/API/Event/srcElement @JacobNelson
Mohammed Gadi
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.