如何通过角度2中的函数触发事件单击输入类型="文件"?

Trầ*_*ơng 8 html javascript typescript angular

我在Html文件中有这个代码.

<input #fileInput type="file"  />
Run Code Online (Sandbox Code Playgroud)

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() {


}

}
Run Code Online (Sandbox Code Playgroud)

我看到这个答案:如何从角度2的按钮点击触发输入文件的点击事件? 当然有效.但我想在triggerFile()函数中触发input type ="file",我使用ViewQuery和nativeElement.click()函数.但它控制此错误"无法读取未定义的属性'nativeElement'".我使用angular2 Rc 1.谢天谢地

Gün*_*uer 10

fileInput引用传递给triggerFile()并在fileInput.click()那里执行:

<input #fileInput type="file"  />
<button type="button" (click)="triggerFile(fileInput)">trigger</button>
Run Code Online (Sandbox Code Playgroud)
triggerFile(fileInput:Element) {
  // do something
  fileInput.click();
}
Run Code Online (Sandbox Code Playgroud)

  • 您可以将`@ViewQuery('fileInput)fileInput:ElementRef;`添加到组件类中,然后您不需要从视图中传递它.使用`this.fileInput.nativeElement.click();`调用click (4认同)

Dan*_*iaz 5

无需在控制器中编写代码

<input #fileInput type="file"  />
<button type="button" (click)="fileInput.click()">trigger</button>
Run Code Online (Sandbox Code Playgroud)