File uploading example using NestJS and Angular 11 - Part 2



This is the second part of the File uploading example using NestJS and Angular 11 - Part 1. In this article, I am going to talk about how to create a client application using Angular 11.

Create a new Angular application using Angular CLI

    • As I mentioned in the previous article, Angular CLI needs to be installed.
    • Then hit the below command to create a new Angular application. 
    • automobile-frontend is my application name.

    ng new automobile-frontend

    Run Angular application

    • Go inside of the automobile-frontend directory.
    • Then hit the below command to run the application.


    ng serve -o

    • Now your client application will run on port 4200 and the default page will be shown. 

    Expected UI

    • I will be using a basic fixed navbar, the navbar component will handle this.
    • The home component will be used as a parent component for routing

    Create the basic structure

    • I am going to create some components for this application.

    Create components

    • I am going to create three components, called home, navbar, and upload.
    • Create the home component. 

    ng g c home --skip-tests=true

    • Create the upload component

    ng g c upload --skip-tests=true

    • Create the navbar component

    ng g c navbar --skip-tests=true

    • I skipped tests when creating the above components.



    • The above screenshot shows all components that we have created and their selectors (selector name can be changed. But I will use default selectors.
      • app-home
      • app-navbar
      • app-upload

    Install Bootstrap

    • I am using a simple Bootstrap template in this application.
    • So we need to install Bootstrap.
    • You can install Bootstrap or you can use ng-bootstrap as well. But I am using Bootstrap 3, old but simple to use. You can use any preferred version.

    npm install bootstrap@3.3.7

    • Then add @import "~bootstrap/dist/css/bootstrap.css"; into the styles.css file
    • I am not going to add jquery for this project.

    Add a template for the navbar

    • I will use a basic bootstrap navbar template.

            <nav class="navbar navbar-default">
            <div class="container-fluid">
            <div class="navbar-header">
            <a class="navbar-brand" href="/">Automobile system</a>
            </div>

            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
            <ul class="nav navbar-nav">
            <li><a href="/">Home <span class="sr-only">(current)</span></a></li>
            <li><a [routerLink]="'/upload'" routerLinkActive="active">Upload file</a></li>
            </ul>
            </div>
            </div>
            </nav>

    • In the future, I will add more to this navbar. 
    • As you can see I've used routerLink to route the upload component
    • Here is the app-routing.module.ts file
    • In this file, I have created a route to the upload component.
    • Then /upload will route to the upload component. 

            import { NgModule } from '@angular/core';
            import { RouterModule, Routes } from '@angular/router';
            import { UploadComponent } from './upload/upload.component';

            const routes: Routes = [
            {
            path: 'upload',
            pathMatch: 'full',
            component: UploadComponent
            }
            ];

            @NgModule({
            imports: [RouterModule.forRoot(routes)],
            exports: [RouterModule]
            })
            export class AppRoutingModule { }


    Refactor home-component

    • The home-component will be used for routing.
    • All other components except nav-bar will be inside of the home-component. 
    • Changes are not required for the home.component.ts file.
    • The only thing you need to do is, add the following line to the home.component.html file

    <router-outlet></router-outlet>


    Add upload functionality

    • Once the user clicks on the upload file in the navbar, the upload component will take the user.
    • In the upload component, I am going to handle the file uploading form and its functionalities. 
    • Look at the upload.component.html file

            <div class="container container-table">
            <div class="row vertical-center-row">
            <div class="text-center col-md-4 col-md-offset-4">
            <form [formGroup]="myForm" (ngSubmit)="submit()">

            <div class="form-group">
            <label for="file">Please select the csv file</label>
            <input formControlName="file" id="csv" type="file" class="form-control"
            (change)="onFileChange($event)" multiple>
            </div>

            <button class="btn btn-primary" type="submit">Upload</button>
            </form>

            </div>
           </div>
            </div>


    • Here I am using a simple reactive form.
    • Now check how the upload.component.ts file looks like.

            import { Component } from '@angular/core';
            import { FormControl, FormGroup, Validators } from '@angular/forms';
            import { HttpClient } from '@angular/common/http';

            @Component({
            selector: 'app-upload',
            templateUrl: './upload.component.html',
            styleUrls: ['./upload.component.css']
            })
            export class UploadComponent {

            myForm = new FormGroup({
            file: new FormControl('', [Validators.required]),
            fileSource: new FormControl('', [Validators.required])
            });

            constructor(private http: HttpClient) { }

            get f() {
            return this.myForm.controls;
            }

            onFileChange(event: any) {
            if (event.target.files.length > 0) {
            const csv = event.target.files[0];
            this.myForm.patchValue({ fileSource: csv });
            }
            }

            submit() {
            const formData = new FormData();
            formData.append('csv', this.myForm.get('fileSource')!.value);

            this.http.post('http://localhost:3000/api/vehicles/upload', formData)
            .subscribe((data) => {
            if (data === null) {
            alert("Data import error")
            } else {
            alert("Data imported successfully")
            }
            }
            )
            }
            }



    • The HttpClient is used to call our back-end API for file uploading and our back-end service also need to start. The back-end service will run on port 3000 (http://localhost:3000/api/vehicles/upload)
    • To make this work, you need to import used modules in the app.module.ts


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

            import { AppRoutingModule } from './app-routing.module';
            import { AppComponent } from './app.component';
            import { HomeComponent } from './home/home.component';
            import { UploadComponent } from './upload/upload.component';
            import { NavbarComponent } from './navbar/navbar.component';
            import { FormsModule, ReactiveFormsModule } from '@angular/forms';
            import { HttpClientModule } from '@angular/common/http';

            @NgModule({
            declarations: [
            AppComponent,
            HomeComponent,
            UploadComponent,
            NavbarComponent
            ],
            imports: [
            BrowserModule,
            AppRoutingModule,
            FormsModule,
            HttpClientModule,
            ReactiveFormsModule
            ],
            providers: [],
            bootstrap: [AppComponent]
            })
            export class AppModule { }


    • Now we are all set to launch.
    • If you have any doubts or missing parts, please check the given Github link at the end of this article. 

    Test the application

    • Hit ng serve -o to launch the application.
    • Now the UI will look like this.





    • Now you can select a CSV file (I already shared a CSV file in the GIT repository) and upload it to check everything works fine. 
    • You may check consoles for any errors and if you are getting any errors, please check your code with my code.
    • Here is the link for the Github repository for the complete project.

    GIT repository


    In the next article, I will be doing the same scenario using the BullJS, the queue operations with NestJS. 





    File uploading example using NestJS and Angular 11 - Part 2 File uploading example using NestJS and Angular 11 - Part 2 Reviewed by Ravi Yasas on 4:44 PM Rating: 5

    No comments:

    Powered by Blogger.