2016-07-08 7 views
7

मेरे पास यह कोड HTML फ़ाइल में है। बेशक how to trigger click event of input file from button click in angular 2? यह काम किया:ईवेंट ट्रिगर कैसे करें इनपुट प्रकार = "फ़ाइल" पर कोणीय 2 में फ़ंक्शन द्वारा क्लिक करें?

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


} 

} 

मैं इस सवाल का जवाब देखें। लेकिन मैं ट्रिगरफाइल() फ़ंक्शन में इनपुट प्रकार = "फ़ाइल" ट्रिगर करना चाहता हूं और मैं ViewQuery और nativeElement.click() फ़ंक्शन का उपयोग करता हूं। लेकिन यह इस त्रुटि को कंसोल करता है "अपरिभाषित की मूल संपत्ति 'मूल' पढ़ नहीं सकता '। मैं angular2 आरसी 1 का उपयोग करें। मदद के लिए धन्यवाद।

+1

आप होगा बहुत कुछ होना स्पष्ट, नियंत्रण, क्या से ट्रिगर किया? – adeneo

+0

@adeneo मैंने अपना प्रश्न संपादित किया है। धन्यवाद । –

उत्तर

9

triggerFile() को fileInput संदर्भ दर्रा और fileInput.click() वहाँ के बजाय कार्य करें:

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

यह अच्छी तरह से काम किया। बहुत बहुत धन्यवाद । –

+0

क्या मैं आपसे एक और सवाल पूछ सकता हूं? मैं अपनी ts फ़ाइल में फ़ंक्शन द्वारा इवेंट क्लिक कैसे ट्रिगर कर सकता हूं (बटन पर क्लिक करके नहीं)? –

+2

आप '@ViewQuery ('fileInput) फ़ाइल इनपुट जोड़ सकते हैं: ElementRef;' अपने घटक वर्ग में, तो आपको इसे दृश्य से पास करने की आवश्यकता नहीं है। 'This.fileInput.nativeElement.click();' –

2

नियंत्रक में कोड लिखने की कोई आवश्यकता नहीं है

<input #fileInput type="file" /> 
<button type="button" (click)="fileInput.click()">trigger</button> 
संबंधित मुद्दे