问题描述
这是我的输入标签的样子:
This is how my input tag looks like:
<input type="file" placeholder="File Name" name="filename" (change)="onChange($event)">
<button>Reset</button>
我想在Angular 2中重置所选文件.非常感谢您的帮助.让我知道您是否需要更多详细信息.
I want to reset the selected file in Angular 2. Help would be greatly appreciated. Let me know if you need more details.
P.S.
我可以从$event
参数获取文件详细信息,并将其保存在typescript变量中,但是此变量未绑定到输入标签.
I could get file details from $event
parameters and save it in a typescript variable, but this variable is not bound to the input tag.
推荐答案
您可以使用ViewChild
访问组件中的输入.首先,您需要在输入中添加#someValue
以便可以在组件中读取它:
You can use ViewChild
to access the input in your component. First, you need to add #someValue
to your input so you can read it in the component:
<input #myInput type="file" placeholder="File Name" name="filename" (change)="onChange($event)">
然后在您的组件中,需要从@angular/core
导入ViewChild
:
Then in your component you need to import ViewChild
from @angular/core
:
import { ViewChild } from '@angular/core';
然后使用ViewChild
来访问模板的输入:
Then you use ViewChild
to access the input from template:
@ViewChild('myInput')
myInputVariable: ElementRef;
现在您可以使用myInputVariable
重置所选文件,因为它是对#myInput
输入的引用,例如创建方法reset()
,该方法将在按钮的click
事件上调用:
Now you can use myInputVariable
to reset the selected file because it's a reference to input with #myInput
, for example create method reset()
that will be called on click
event of your button:
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 ,因此不可能仅从数组中删除项目.在这里工作柱塞.
First console.log
will print the file you selected, second console.log
will print an empty array because this.myInputVariable.nativeElement.value = "";
deletes selected file(s) from the input. We have to use this.myInputVariable.nativeElement.value = "";
to reset the value of the input because input's FileList
attribute is readonly, so it is impossible to just remove item from array. Here's working Plunker.
这篇关于如何在Angular 2中使用输入标签文件类型重置所选文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!