You can easily bind the $event object in Angular to an element, say a file input element, and pass the event information to your component event handler. This helps in understanding the type, name, size etc. of the files, before you use the files in your application.
Adding $event Object to File Input Element (app.component.html)
I want to show some information (like the name, size and type) of each file immediately after the user selects a file. Therefore, I need to bind the $event object to the file input elements change event. This is how my code looks in my applications template.
<input type="file" id="file" multiple
(change)="getFileDetails($event)"
style="margin: 8px;
padding: 8px 5px;
color: #333;
width: auto;
cursor: pointer;"
>
The code above listens to the change event and passes the information (via $event object) as parameter to a function named getFileDetails(), which I have written in my component class.
My Component Class (app.component.ts)
The function getFileDetails() inside my component class looks like this.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { ngOnInit () { } getFileDetails (event) { for (var i = 0; i < event.target.files.length; i++) { var name = event.target.files[i].name; var type = event.target.files[i].type; var size = event.target.files[i].size; var modifiedDate = event.target.files[i].lastModifiedDate; console.log ('Name: ' + name + "\n" + 'Type: ' + type + "\n" + 'Last-Modified-Date: ' + modifiedDate + "\n" + 'Size: ' + Math.round(size / 1024) + " KB"); } } }
The $event object provides some predefined properties that I have used to get the info. In this way you can check the file size, type etc. before uploading or doing anything with files.