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

aka*_*ash 67 angular

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

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

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

PS

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

Ste*_*ota 161

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

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

然后在您的组件中,您需要ViewChild@angular/core以下位置导入:

import { ViewChild } from '@angular/core';
Run Code Online (Sandbox Code Playgroud)

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

@ViewChild('myInput')
myInputVariable: ElementRef;
Run Code Online (Sandbox Code Playgroud)

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

reset() {
    console.log(this.myInputVariable.nativeElement.files);
    this.myInputVariable.nativeElement.value = "";
    console.log(this.myInputVariable.nativeElement.files);
}
Run Code Online (Sandbox Code Playgroud)

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

  • `myInputVariable`的确是`ElementRef`类型 (3认同)
  • 这足以清除价值`this.myInputVariable.nativeElement.value ="";`?/ (2认同)
  • 在角度 8 @ViewChild('delDocModal', {static: false})delDocModal: ElementRef; (2认同)

2To*_*oad 16

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

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

  // Clear the input
  event.target.value = null;
}
Run Code Online (Sandbox Code Playgroud)

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

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


Edm*_*ake 12

实现它的一种方法是将输入包装在<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()
  }
}
Run Code Online (Sandbox Code Playgroud)

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


Adm*_*mir 10

Angular 5

HTML

<input type="file" #inputFile>

<button (click)="reset()">Reset</button>
Run Code Online (Sandbox Code Playgroud)

模板

@ViewChild('inputFile') myInputVariable: ElementRef;

reset() {
    this.myInputVariable.nativeElement.value = '';
}
Run Code Online (Sandbox Code Playgroud)

按钮不是必需的.您可以在更改事件后重置它,它仅用于演示