File Uploads with Angular Reactive Forms

Austin
Austin
Feb 15, 2018 · 2 min read
Image for post
Image for post

Reactive forms are great for basic inputs but what if we want to use them with file uploads? A really good reason to bind these two things together is because we might want to do some validation to prevent the form from being submitted unless its been touched and we have a file uploaded.

To get started lets make a component that has a field called file.

In this component, we disable the submit button until the form has been touched and also if the form is invalid. Next, lets wire up the file input by adding a (change) event like:

<input type="file" (change)="onFileChange($event)" />

then in our component lets add a onFileChange method that will read the contents from the input file.

This method uses the FileReader to read the contents of the file and take the result and patch the form with value. Your server can then take this and decode it. Also, you might notice I call cd.markForCheck(), this is because my zone doesn’t catch the onload event so we need to manually call it to update otherwise the submit button won’t be enabled.

Lets put it all together now:

Its important to note, this is not always best if you have VERY large files but for simple stuff like images this is a good way to keep things simple.

Image for post
Image for post
I’m #ngPanda

I hope you enjoyed the post, if you liked it follow me on and for more JavaScript tips/opinions/projects/articles/etc!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store