How to trigger the file upload input in Angular 4? I'm trying, but it's not working.
Instead of input button, I have to click on div and trigger the input type button.
app.html:
<input id="custom-input" type="file" >
<div (click)="myEvent(custom-input)">
Click here to upload file
</div>
app.ts:
myEvent(event) {
alert("event");
event.nativeElement.click();
}
The easiest way is to check if there are any files in temporary memory. If you want to get the change event every time user clicks the file input you can trigger it. Show activity on this post. In my case i had to hide submit button while users were selecting images.
You can restrict the maximum allowed file size (in bytes) by using the maxFileSize property. If the selected file exceeds the maximum size, an error message will be displayed.
<input
hidden
type="file"
#uploader
(change)="uploadFile($event)"
/>
<button (click)="uploader.click()">
Upload
</button>
Then in your component you can use the $event
:
uploadFile($event) {
console.log($event.target.files[0]); // outputs the first file
}
HTML Template (attachment.component.html)
<input
style="display: none"
type="file"
multiple
(change)="onFileChanged($event)"
#fileInput
/>
<input
type="button"
class="upload-button"
value="Upload attachment(s)"
(click)="fileInput.click()"
/>
Handling in Typescript(attachment.component.ts)
Third argument passed for the post call is for tracking the progress of upload using the event which we get subscribe to
onFileChanged(event) {
this.selectedFile = event.target.files[0];
this.http.post('url', uploadData, {
reportProgress: true,
observe: 'events'
}).subscribe(event => {
console.log('uploaded successfully');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With