

This UI could be a dialog, a drag and drop zone, or like in the case of our component, just a styled button: This plain input text is hidden from the user, as we can see in the component CSS:īelow the hidden file input, we have the file-upload container div, which contains the actual UI that the user will see on the screen.Īs an example, we have built this UI with Angular Material components, but of course, the alternative file upload UI could take any form that you like. On top, we have a plain file input, that is used to open the file upload dialog and handle the change event. This user interface is split up into two separate parts. Here is what the template of an initial file upload component could look like: Building the User Interface of a File Upload Componentīecause a plain input of type file is impossible to style properly, what we end up doing is hiding it from the user, and then building an alternative file upload UI that uses the file input behind the scenes. Now that we know how all the standard file upload browser functionality works, let's see how can we build a nice Angular component to encapsulate it. Instead, we will need to trigger an HTTP request ourselves, in response to the change event.

When the change event gets triggered, the file is not automatically uploaded to the backend by the browser. Here is the output that we see on the console after the user selects a file: This event will then contain the list of files that the user selected on the target.files property. When the user chooses a file using the file upload dialog, an event of typeĬhange will be emitted. This is default browser behavior that can't be changed, and that is why we usually don't see this plain file input on all the interfaces that we use daily, like Gmail, etc.īecause this file input is impossible to style properly, the most common option is to actually never show it to the end-user, as we will see. Some styles applied to it can't be changed, and we can't even change the text on the button! The problem with this plain file input is that by default it's very hard to style. With this file input box, you can select a file from your file system, and then with a bit of Javascript, you can already send it to a backend. This input will allow the user to open a browser file selection dialog and select one or more files (by default, only one file). The key ingredient for uploading files in a browser is a plain HTML input of type file:
#Angular 2 file uploader how to
In order to build an Angular file upload component, we need to first understand how to upload files in plain HTML and Javascript only, and take it from there. So without further ado, let's get started learning how to build an Angular file upload component! How to Upload Files in a Browser

Next, after a click on the submit button of the form. We'll listen for the input onchange event, and add the selected file to a list. We'll implement a simple reactive form using formGroup.
