最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to trigger event click at input type="file" by function in angular 2? - Stack Overflow

programmeradmin2浏览0评论

I have this code in Html file .

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


}

}

I see this answer : how to trigger click event of input file from button click in angular 2? Of course it worked . But I want to trigger input type="file" in triggerFile() function and I use ViewQuery and nativeElement.click() function . but it console this error "Cannot read property 'nativeElement' of undefined" . I use angular2 Rc 1 . thank for help .

I have this code in Html file .

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


}

}

I see this answer : how to trigger click event of input file from button click in angular 2? Of course it worked . But I want to trigger input type="file" in triggerFile() function and I use ViewQuery and nativeElement.click() function . but it console this error "Cannot read property 'nativeElement' of undefined" . I use angular2 Rc 1 . thank for help .

Share Improve this question edited May 23, 2017 at 11:46 CommunityBot 11 silver badge asked Jul 8, 2016 at 8:08 Trần DươngTrần Dương 5352 gold badges6 silver badges16 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 10

Pass the fileInput reference to triggerFile() and do the fileInput.click() there instead:

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

No need to write code in controller

<input #fileInput type="file"  />
<button type="button" (click)="fileInput.click()">trigger</button>
发布评论

评论列表(0)

  1. 暂无评论