Create Custom Material File Browse/Upload UI in Angular 14

Angular Material File Upload UI tutorial, throughout this detailed tutorial, you will comprehend how to profoundly add a File Upload/Browse button using a form input text element to display chosen files in conjunction with angular material UI components.

Angular Material is a great library that offers tons of UI components; i found a lack of better file uploading components; however, if you are using Bootstrap library, you can find it there.

Hence, to cater the need of File upload UI, we will create a custom File Upload control that you can use for file uploading tasks in angular.

Angular Material 13 Custom File Upload UI Example

In this tutorial, you will be taught all the steps gradually to create a custom File upload UI control in angular using angular material user interface components, so let’s start this tutorial.

  • Step 1: Install Angular App
  • Step 2: Add Angular Material Package
  • Step 3: Add Material Components
  • Step 4: Create File Browse Upload Form
  • Step 5: Add Custom Style in File Upload Input
  • Step 6: Start Application

Install Angular App

First, ensure to install angular CLI to get along with angular, use the recommended command to commence the installation:

npm install -g @angular/cli

Thereafter, begin the angualr project installation:

ng new angular-demo-app

Move into the project folder:

ng new angular-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Add Angular Material Package

Adding material library in angular is easy; execute the suggested command from the console screen:

ng add @angular/material

Answer the question accordingly to install material package with necessary modules:

  1. Choose a prebuilt theme name or “custom” for a custom theme:

    You can choose from prebuilt material design themes or set up an extensible custom theme.

  2. Set up global Angular Material typography styles:

    Whether to apply the global typography styles to your application.

  3. Set up browser animations for Angular Material:

    Importing the BrowserAnimationsModule into your application enables Angular’s animation system. Declining this will disable most of Angular Material’s animations.

Open src/styles.scss file and add the material CSS for enabling the prebuilt theme:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

Add Material Components

Import the essential material packages for building file upload control such as MatInputModule, MatButtonModule, MatFormFieldModule, MatToolbarModule likewise register these components in imports array.

Open and add the reccommended code in app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { MatButtonModule } from '@angular/material/button';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatToolbarModule,
    MatButtonModule,
    MatFormFieldModule,
    MatInputModule,
    FormsModule    
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }

Create File Browse Upload Form

Head over to app.component.html file, inside here add the given code:

<mat-form-field>

  <div class="fileControl-wrapper">

    <mat-toolbar>
      <input matInput [(ngModel)]="uploadFileName" readonly name="File" />

      <button mat-flat-button color="accent">Pick File</button>
    </mat-toolbar>

    <input type="file" #uploadControl id="fileControlInput" (change)="onFileChange($event)" name="fileControlInput"
      multiple="multiple" accept="image/*" />

  </div>

</mat-form-field>

Define the image upload component with the mat-form-field directive; the ngModel directive makes the two-way data binding possible and attached with matInput control.

Add the button element with the mat-flat button; the color property decides the button color; this button takes the command to upload the file.

File type validation is applied using the accept directive followed by image/* property; you can upload the multiple images at once it is possible with multiple tag, the file will be updated when the user clicks on the input control, the change event is handling this process.

Open app.component.ts file and insert the following code:

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {

  @ViewChild('uploadControl') uploadControl: ElementRef;
  uploadFileName = 'Choose File';

  onFileChange(e: any) {

    if (e.target.files && e.target.files[0]) {

      this.uploadFileName = '';
      Array.from(e.target.files).forEach((file: File) => {
        this.uploadFileName += file.name + ',';
      });

      const fileReader = new FileReader();
      fileReader.onload = (e: any) => {
        const img = new Image();
        img.src = e.target.result;
        img.onload = res => {

          const imgBase64Path = e.target.result;

        };
      };
      fileReader.readAsDataURL(e.target.files[0]);

      this.uploadControl.nativeElement.value = "";
    } else {
      this.uploadFileName = 'Choose File';
    }
  }

}

Add Custom Style in File Upload Input

Next, you have to add a little bit styling using the CSS, hence get inside the app.component.scss file and inject the following code:


.fileControl-wrapper {
    position: relative;
    width: 360px;

    .mat-form-field {
        width: 100%;
    }

    .mat-toolbar-single-row {
        height: auto !important;
        background: transparent;

        button {
            width: 40%;
            text-align: center;
        }
    }
}

#fileControlInput {
    position: absolute;
    cursor: pointer;
    z-index: 10;
    opacity: 0;
    height: 100%;
    width: 100%;
    left: 0px;
    top: 0px;
}

Start Application

You can now test the app but make sure to start the development server of angular app:

ng serve

Start the app on the recommended URL on the browser:

http://localhost:4200

Angular Material Custom File Upload UI Example

Conclusion

The Angular File Upload UI tutorial is over.

In this tutorial, we explained how to build a custom file browse or upload UI control using angular material components; also, we learned to add custom styling in the material form input control.