如何在Angular 2中使用输入标记文件类型重置所选文件?
这是我的输入标签的样子:
<input type="file" placeholder="File Name" name="filename" (change)="onChange($event)"> <button>Reset</button> 我想在Angular 2中重置所选文件.非常感谢帮助.如果您需要更多详细信息,请告诉我们. 附: 我可以从$event参数中获取文件详细信息并将其保存在typescript变量中,但此变量未绑定到输入标记.
您可以使用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输入的引用,例如create button 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |