我在 Html 文件中有这段代码。
<input #fileInput type="file" />
demo.ts
import {
Component,
Inject,
OnInit,
ElementRef,
Renderer,
ViewQuery
} from '@angular/core';
@Component({
selector: 'demo',
templateUrl: 'client/dev/demo/demo.html',
})
export class DemoComponent implements OnInit{
@ViewQuery('fileInput') fileInput:ElementRef;
constructor(){}
triggerFile(){
// do something
// trigger input type="file" here
this.fileInput.nativeElement.click();
}
ngOnInit() {
}
}
我看到这个答案:how to trigger click event of input file from button click in angular 2? 当然有效。但我想在 triggerFile() 函数中触发 input type="file"并且我使用 ViewQuery 和 nativeElement.click() 函数。但它控制了这个错误“无法读取未定义的属性‘nativeElement’”。我使用 angular2 Rc 1 。感谢您的帮助。
最佳答案
将 fileInput
引用传递给 triggerFile()
并在那里执行 fileInput.click()
:
<input #fileInput type="file" />
<button type="button" (click)="triggerFile(fileInput)">trigger</button>
triggerFile(fileInput:Element) {
// do something
fileInput.click();
}
关于javascript - 如何通过 Angular 2中的函数触发输入类型="file"的事件点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38261859/