gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:46:01 24 4
gpt4 key购买 nike

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

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

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

附言

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

最佳答案

您可以使用 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 属性是readonly,所以不可能只从数组中删除项目。这是工作 Plunker .

关于angular - 如何在 Angular 2 中使用输入标签文件类型重置所选文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com