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.