Build Angular Material 13 File Browse/Upload UI Component
This is an Angular 13 step-by-step tutorial assimilate the comprehension in your neurons about creating the browse/file upload UI (user interface) using Angular Material 13 components such as MatButtonModule, MatInputModule, MatFormFieldModule, and MatToolbarModule.
Angular Material has offered some of the outstanding UI components, saves lots of your time; however, it doesn’t offer the File uploading component yet.
Maybe this will be taken into consideration in the future update, but for now, we are going to create a file uploading component using material components and tweaking a little bit of CSS in Angular.
Create Angular Project
Angular CLI is needed to create a new angular application; if already installed, skip it.
npm install -g @angular/cli
We are all set! Now, respectively run the defined command to install a new angular application.
ng new angular-material-file-upload-example
Move inside the application root.
cd angular-material-file-upload-example
Install Angular Material
Installing angular material is a no-brainer; just execute the following command via command prompt:
ng add @angular/material
Select the theme, typography and browser animations.
? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink
❯ Indigo/Pink [ Preview: https://material.angular.io?theme=indigo-pink ]
Deep Purple/Amber [ Preview: https://material.angular.io?theme=deeppurple-amber ]
Pink/Blue Grey [ Preview: https://material.angular.io?theme=pink-bluegrey ]
Purple/Green [ Preview: https://material.angular.io?theme=purple-green ]
? Set up global Angular Material typography styles? Yes
? Set up browser animations for Angular Material? Yes
Import Material Modules in Separate Module File
To make things simpler, we create separate angular material modules file, import all the material modules inside of it.
Create app/angular-material.module.ts file and place the following code inside of it.
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatToolbarModule } from '@angular/material/toolbar';
const materialModules = [
MatIconModule,
MatButtonModule,
MatInputModule,
MatFormFieldModule,
MatProgressBarModule,
MatToolbarModule,
];
@NgModule({
imports: [CommonModule, ...materialModules],
exports: [...materialModules],
})
export class AngularMaterialModule {}
In general, register the material module file in the app.module.ts file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
AngularMaterialModule,
FormsModule,
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
We have spruced up the basic configuration now. We are all set to create the angular material file browser control in angular application.
Create Static File Upload in Form Component
Create a browser/file upload component inside the mat-form-field; we are also taking the mat-toolbar help. A user can upload multiple files through this component.
The uploadFileEvt() method is bound to change the event as soon as any file is uploaded through it. It will sync with FileReader API and browse the files via the input field.
Insert the code in app.component.html file to define the file upload component.
<mat-form-field>
<div>
<mat-toolbar>
<!-- Display files names -->
<input matInput [(ngModel)]="fileAttr" readonly name="name" />
<!-- Browse Button -->
<button mat-flat-button color="primary">Browse File</button>
</mat-toolbar>
<!-- Fetch selected filed on change -->
<input
type="file"
#fileInput
id="uploadFile"
(change)="uploadFileEvt($event)"
name="uploadFile"
multiple="multiple"
accept="image/*"
/>
</div>
</mat-form-field>
Add the code in app.component.ts file.
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {
@ViewChild('fileInput') fileInput: ElementRef;
fileAttr = 'Choose File';
uploadFileEvt(imgFile: any) {
if (imgFile.target.files && imgFile.target.files[0]) {
this.fileAttr = '';
Array.from(imgFile.target.files).forEach((file: any) => {
this.fileAttr += file.name + ' - ';
});
// HTML5 FileReader API
let reader = new FileReader();
reader.onload = (e: any) => {
let image = new Image();
image.src = e.target.result;
image.onload = (rs) => {
let imgBase64Path = e.target.result;
};
};
reader.readAsDataURL(imgFile.target.files[0]);
// Reset if duplicate image uploaded again
this.fileInput.nativeElement.value = '';
} else {
this.fileAttr = 'Choose File';
}
}
}
You might get compilation error so to get rid of the compilation error. Head over to tsconfig.json and set:
"compilerOptions": {
"strictPropertyInitialization": false,
}
Style File Upload UI Component
The file upload component has been built, its time to make it look better and it can be done using some custom CSS code. So, add the code in the app.components.css file.
.mat-form-field {
margin: 40px 0;
width: 500px !important;
}
.mat-toolbar-single-row {
height: auto !important;
background: transparent;
}
.mat-toolbar-single-row button {
width: 200px;
}
.mat-form-field {
width: 100%;
}
#uploadFile {
top: 0px;
left: 0px;
width: 100%;
z-index: 9;
opacity: 0;
height: 100%;
cursor: pointer;
position: absolute;
}
Eventually, we are done with everything, Its time to start the application and check out what we have built.
ng serve --open
This will be the final result:
Summary
Finally, we have seen how easy it is to build a File Upload component. We can easily transform some material components into file browser control.