10

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 .

0

2 Answers 2

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();
}
Sign up to request clarification or add additional context in comments.

15 Comments

Can I ask you one more question ? how can I trigger event click by function in my ts file ( not by click on button )?
You can add @ViewQuery('fileInput) fileInput:ElementRef; to your component class, then you don't need to pass it from the view. Invoke the click using this.fileInput.nativeElement.click();
It doesn't contain the @ViewQuery(...
Sorry, it's after ngAfterViewInit() for @ViewChild. I missed that you had it in ngOnInit(), that is still too early.
Call triggerFile() in ngAfterViewInit() not in ngOnInit()
|
6

No need to write code in controller

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.