javascript - 如何通过 Angular 2中的函数触发输入类型="file"的事件点击?

标签 javascript html typescript angular

我在 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/

相关文章:

javascript - 蛇吃食物(HTML5 Canvas 游戏)

html - 当选择是最后一项时, float Div 无法正确换行

带有 document.querySelectorAll 和 filter() 的 javascript 函数无法正常工作

html - Express.js 不发送 css 文件

typescript - 无法在 TypeScript 项目中使用 @faker-js/faker —— 未定义 —— 但旧的 "faker"导入可以工作。为什么?

javascript - 仅在 Android 上显示 html5 视频控件

javascript - Jquery Accordion 默认不折叠

typescript - 可选类型的立即解构参数?

javascript - 设置文件名并在新选项卡中打开 blob pdf 类型

javascript - 根据内部数组对数组进行排序