这是我的输入标签的样子:
<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.
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.srcElement
为event.target
,现在srcElement
已弃用
Edm*_*ake 12
实现它的一种方法是将输入包装在<form>
标签中并重置它.
我不考虑THR形式连接到NgForm
或FormControl
两种.
@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)
按钮不是必需的.您可以在更改事件后重置它,它仅用于演示
归档时间: |
|
查看次数: |
66918 次 |
最近记录: |