Material Dashboard in Angular

Material Dashboard in Angular

In this article we will learn how to create & use material dashboard in angular. Please follow our previous article How to use angular material in angular. If you are new to angular then please explore our Angular Series where we discussed step by step process of angular from beginner to advance level.

  • We create a sample angular 9 application and there use in-built angular dashboard functionality.
  • Here we can see how to add angular material dashboard dynamically with card. We can do change the dashboard card columns and rows dynamically.

Add Material Design in Angular

To create the angular application use the below command. ng-material-dashboard is the project name.

ng new ng-material-dashboard

To add the material design in angular just follow the below command. Also you can find the details about our previous article How to use angular material in angular.

ng add @angular/material

After type the command in terminal window and hit enter then a prompt will ask to choose which material template want to install into the application like this. Let’s install first one “Indigo/Pink” you can chhose any other theme just navigate to the link.

material theme

Generating a Material Dashboard

To generate a material dashboard use the below command. This command should create a starter dashboard component.

Synatax

ng generate @angular/material:material-dashboard --name = <Name of Dashboard>

material-dashboard is a starter component, which generates a group of the materialized components in the form of the dashboard by just providing a name. To create the dashboard run the below command

ng generate @angular/material:material-dashboard --name material-dashboard

And as you can see in the console, there are a few files created inside the app directory with a component name provided. The file structure looks like the below screen.

material-dashboard

After installing this you can see the material-dashboard ts, html and css file automatically created.

Materiel Dashboard component

app.module.ts

You can see here when the material-dashboard component is created it automatically add the required module inside app.module.ts

materiel-app-module

material-dashboard.component.ts

In the below typescript we create a Cards list that return how many columns and rows. You can change the column and row to set dynamically.

import { Component } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
@Component({
  selector: 'app-material-dashboard',
  templateUrl: './material-dashboard.component.html',
  styleUrls: ['./material-dashboard.component.css']
})
export class MaterialDashboardComponent {
  /** Based on the screen size, switch from standard to one column per row */
  cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
    map(({ matches }) => {
      if (matches) {
        return [
          { title: 'Card 1', cols: 1, rows: 1 },
          { title: 'Card 2', cols: 1, rows: 1 },
          { title: 'Card 3', cols: 1, rows: 1 },
          { title: 'Card 4', cols: 1, rows: 1 }
        ];
      }
      return [
        { title: 'Card 1', cols: 2, rows: 1 },
        { title: 'Card 2', cols: 1, rows: 1 },
        { title: 'Card 3', cols: 1, rows: 2 },
        { title: 'Card 4', cols: 1, rows: 1 }
      ];
    })
  );
  constructor(private breakpointObserver: BreakpointObserver) {}
}

material-dashboard.component.html

The below snippet is a basic building block which was generated by the component generator. Dynamically bind the cards from material-dashboard.component.ts and using *ngFor iterate the result through material components.

<div class="grid-container">
  <h1 class="mat-h1">Dashboard</h1>
  <mat-grid-list cols="2" rowHeight="350px">
    <mat-grid-tile *ngFor="let card of cards | async" [colspan]="card.cols" [rowspan]="card.rows">
      <mat-card class="dashboard-card">
        <mat-card-header>
          <mat-card-title>
            {{card.title}}
            <button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
              <mat-icon>more_vert</mat-icon>
            </button>
            <mat-menu #menu="matMenu" xPosition="before">
              <button mat-menu-item>Expand</button>
              <button mat-menu-item>Remove</button>
            </mat-menu>
          </mat-card-title>
        </mat-card-header>
        <mat-card-content class="dashboard-card-content">
          <div>Card Content Here</div>
        </mat-card-content>
      </mat-card>
    </mat-grid-tile>
  </mat-grid-list>
</div>

material-dashboard.component.css

This style sheet file contains different classes to provide different positioning and directions throughout the page.

.grid-container {
  margin: 20px;
}
.dashboard-card {
  position: absolute;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
}
.more-button {
  position: absolute;
  top: 5px;
  right: 10px;
}
.dashboard-card-content {
  text-align: center;
}

These files are automatically generated for creating a Material Dashboard.

Now, the last step is to execute our dashboard app. For that, just go to the app.component.html file and remove all of the content and just add the material-dashboard tag like below;

<app-material-dashboard> </app-material-dashboard>

All the changes has been made, let’s run the application and see the output like below;

Material starter Dashboard template

You can do place the dynamic content/image into the card accordingly in material-dashboard.component.ts. Let’s say we add a image field in card like below;

return [
        { title: 'Card 1', cols: 2, rows: 1, imagepath: '/assets/img1.png' },
        { title: 'Card 2', cols: 1, rows: 1, imagepath: '/assets/img2.png' },
        { title: 'Card 3', cols: 1, rows: 2, imagepath: '/assets/img3.png' },
        { title: 'Card 4', cols: 1, rows: 1 , imagepath: '/assets/img4.png' }
      ];

And in the material-dashboard.component.html add like this.

Image add
Image add

After run the application you can see the image are displayed on the card. According to your dashboard design you can do the stuff.

Image bind on Card

Summary

So far this article we discuss how to use material dashboard in angular. If have any suggestion about this article please give your feedback.

That’s a wrap for this article. I hope that it cleared about Material Dashboard in Angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Export data into PDF in ASP.NET MVC
Export-Data-into-PDF-SERVICE

In this example we use Dapper ORM to fetch the data from database and using the data we export into Read more

How to read external JSON file in Jquery AJAX
Javascript-Jquery-Ajax

This article explain how to read external json file. There are many ways to store JSON data in our application. Read more

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

Export Data to Excel in Angular- Beginner’s Guide

Export Data to Excel in Angular- Beginner’s Guide

In this article explain we discuss how to export data to excel in Angular. We are going to show a demo of excel file download using ExcelJS and File Saver plugin. If you are an Angular developer and looking for export data to excel, then this post will help you more. Please access our previous article Angular 10 with ASP.NET Web API-CRUD Operations.

Find source code in GitHub

When we develop any enterprise application using any technology, the end-user always needs the report data in an Excel file. In enterprise applications, the customer asked us to give a downloadable excel file using various filters.

Environment setup

  • Node version 12.
  • Angular CLI.
  • file-saver npm module.
  • ExcelJS npm module.

Creating New Angular Project and Configuration

Create a new Angular project using the below command and configure the export to excel.

ng new export-excel

Install ExcelJS Plugin

ExcelJS plugin is used to read and write excel file. It is rich in functionality. You can style rows and columns. Even you can add images to excel files. That’s why many people using this library. Install ExcelJS using the below command.

npm install exceljs --save

Install File Saver

FileSaver.js is the solution to saving files on the client-side and is perfect for web apps that generate files on the client. Install file saver plugin using the below command.

npm install file-saver --save

Import ExcelJS and File Saver Plugin

Open the app.component.ts file and import the ExcelJS and File Saver plugin using the below code.

import * as Excel  from 'exceljs';
import * as fs from 'file-saver';

Create a Downloadable Excel File using Dummy Json Data

First, we need data in the JSON format. In our case we create dummy data(you can get the data from the server).

employees = [{
    "name": "Akash Jain",
    "designation": "Developer",
    "Country": "India",
    "email": "akash@gmail.com",
    "age": 25
  },
  {
    "name": "John Smith",
    "designation": "Solution Architect",
    "Country": "England",
    "email": "john.smith@gmail.com",
    "age": 36
  },
  {
    "name": "Raghav Rana",
    "designation": "Developer",
    "Country": "India",
    "email": "raghav.ran@hotmail.com",
    "age": 33
  },
  {
    "name": "Julie Roberts",
    "designation": "Developer",
    "Country": "USA",
    "email": "juile.roberts@gmail.com",
    "age": 36
  },
  {
    "name": "Sundar Raghav",
    "designation": "Solution Consultant",
    "Country": "India",
    "email": "sundar113@gmail.com",
    "age": 38
  },
  {
    "name": "Reba sen",
    "designation": "IT Manager",
    "Country": "Africa",
    "email": "reba.sen@yahoo.com",
    "age": 42
  }
  ]

Configuration on app.component.ts for export to excel

Let’s do all the required things that able to do convert export to excel in app.component.ts file.

import { Component } from '@angular/core';
import * as Excel from 'exceljs';
import * as fs from 'file-saver';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'export-excel';
  emprow: number =1;
  employees = [{
    "name": "Akash Jain",
    "designation": "Developer",
    "Country": "India",
    "email": "akash@gmail.com",
    "age": 25
  },
  {
    "name": "John Smith",
    "designation": "Solution Architect",
    "Country": "England",
    "email": "john.smith@gmail.com",
    "age": 36
  },
  {
    "name": "Raghav Rana",
    "designation": "Developer",
    "Country": "India",
    "email": "raghav.ran@hotmail.com",
    "age": 33
  },
  {
    "name": "Julie Roberts",
    "designation": "Developer",
    "Country": "USA",
    "email": "juile.roberts@gmail.com",
    "age": 36
  },
  {
    "name": "Sundar Raghav",
    "designation": "Solution Consultant",
    "Country": "India",
    "email": "sundar113@gmail.com",
    "age": 38
  },
  {
    "name": "Reba sen",
    "designation": "IT Manager",
    "Country": "Africa",
    "email": "reba.sen@yahoo.com",
    "age": 42
  }
  ]
  downloadExcel() {  
    //create new excel work book
    let workbook = new Excel.Workbook();
    //add name to sheet
    let worksheet = workbook.addWorksheet("Employee Data");
    //add column name
    let header = ["Name", "Designation","Country","Email","Age"]
    let headerRow = worksheet.addRow(header);
    //headerRow.font = { size: 14, bold: true };
    for (let x1 of this.employees) {
      let x2 = Object.keys(x1);
      let temp = []
      for (let y of x2) {
        temp.push(x1[y])
      }
      worksheet.addRow(temp)
    }
    //set downloadable file name
    let fname = "Employee Sheet"
    //add data and file name and download
    workbook.xlsx.writeBuffer().then((data) => {
      let blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      fs.saveAs(blob, fname + '-' + new Date().valueOf() + '.xlsx');
    });
  }
}

Code Explanation

  • Line no. 2-3: We import the require plugins that require to convert data to excel.
  • Line no. 12-54: The employee dummy Json data (You can use data pick from server).
  • Line no. 57 : We create a workbook excel workbook let workbook = new Excel.Workbook();
  • Line no. 59 : From the workbook, we can create a new sheet using the addWorksheet() function like let worksheet = workbook.addWorksheet(“Employee Data”);
  • Line no. 61 : Add column header using the addRow() function. In the JSON data, we added the columns.
  • Line no. 64-71 : Now add the JSON data to the worksheet using the for loop.
  • Line no. 73-79 : Set the file name and call the write function to create a downloadable excel file.

Create Button With Click Event in app.component.html

<div class="content" role="main">
  <div class="container" style="width: 100%;">
    <div class="panel panel-default">
      <div class="panel-heading">Demo on Export to Excel</div>
      <div class="panel-body">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">#</th>
              <th scope="col">Name</th>
              <th scope="col">Designation</th>
              <th scope="col">Country</th>
              <th scope="col">Email</th>
              <th scope="col">Age</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let emp of employees; let ndx = index">
              <th scope="row">{{ndx+1}}</th>
              <td>{{emp.name}}</td>
              <td>{{emp.designation}}</td>
              <td>{{emp.Country}}</td>
              <td>{{emp.email}}</td>
              <td>{{emp.age}}</td>
            </tr>
          </tbody>
        </table>
        <button class="centre btn mc" (click)="downloadExcel()">Export to Excel</button>
      </div>
    </div>
  </div>
</div>

Code Explanation

  • Line no. 6-27: We make a table that should display the JSON data in tabular format. Using For loop we iterate with employee Information.
  • Line no. 28: We create a button that call the TS method downloadExcel()

That’s All. Let’s run the application using command ng s –o and see the result

You can see now, the JSON data is displayed in tabular format and Export to Excel button is there. Now click on this button and you can generate the Excel according to the below image.

What issue may come in ExcelJS and how to deal this ?

I got the below issue while using ExcelJS while run the application.

To overcome the above issue, open the tsconfig.base.json file and make add “node” in type as like below.

Source Code

Click to get Source Code

Summary

In this article we discussed how to export data into excel in Angular . This post will be very helpful if you are looking for a downloadable excel file using Angular. The ExcelJS plugin offers styling rows and columns and even you can add images too. It had many other functionalities too. You can check it out using the below link.

For more details about ExcelJs visit this link.

Latest Post

Export data into Excel in ASP.NET MVC
Export-data-into-Excel

In this example we learn how to export the data into MS Excel in ASP.NET MVC without using any 3rd Read more

Angular 10 with ASP.NET Web API-CRUD Operations
Angular-10-with-ASP.NET-Web-API-CRUD-Operations

Angular CRUD operation using ASP .NET Web API with Entity Framework Code first approach in SQL Server. Beginners guide to Read more

How to create custom pipes in Angular
How to create custom pipes in Angular

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are Read more

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

Angular 10 with ASP.NET Web API-CRUD Operations

Angular 10 with ASP.NET Web API-CRUD Operations

In this article we discuss create a CRUD application using Angular 10 with ASP.NET Web API. CRUD Operations (Insert Update and Delete) will be implemented inside an Asp .NET Web API Using Entity Framework and then consumed from an Angular 10 Application. Also please follow our previous blog post CRUD Operation in ASP.NET Web API with Entity Framework.

Find the Source code on the link

Prerequisite to start

Angular 10 & CLI
– ngx-Toastr (NPM package) & Bootstrap and Font-Awesome Icons
– Visual Studio Code & Visual Studio
– ASP .NET Web API & SQL Server
– Entity Framework

Create ASP.NET Web API Project

Let’s create a ASP.NET Web API Project to connect Angular application. Follow below steps to create ASP.NET Web API project. Open Visual studio choose ASP.NET Web Application and then select Empty template with checked Web API Project.

Create the Model Class

Let’s create a model of customer object. Right click on the Models folder and add the class named as Customer with following properties.

namespace CustomerAPI.Models
{
    [Table("Customer")]
    public class Customer
    {
        [Key]
        public int CustId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
    }
}
  • Here we create the Customer Model with above properties.
  • [Table(“Customer”)] is belong to System.ComponentModel.DataAnnotations.Schema namespace. Here Customer is the table name that we want to create dynamically using EF code first.
  • CustId is the primary key of our entity table so we added as [Key]

After creating the Models class must rebuild the applications. To rebuild the project right click on Project and then click Rebuild.

Adding the API Controller

To do database operations to create, update,read and delete over model class we need to create the controller that should do the CRUD operations for us. To create the Controller right click on the Controllers folder and add a new Controller and in the prompt choose as Web API2 controller with actions, using Entity framework like below. Here we can use in-built entity framework scaffold technique to create CRUD query for us.

After click the Add button a prompt will open to scaffold the model to create CRUD operations and choose Web API2 controller with actions, using Entity Framework.

  • In the Model Class choose the Model, in our case it is customer model class.
  • In the Data Context class, add + symbol and add the CustomerAPI Context.
  • Controller name in our case is CustomerController

After create the scaffold controller automatically it create the CRUD ( Create, Read, Update, Delete ) operations using Customer Model class and CustomerAPI Context class like below.

public class CustomersController : ApiController
    {
        private CustomerAPIContext db = new CustomerAPIContext();

        // GET: api/Customers
        public IQueryable<Customer> GetCustomers()
        {
            return db.Customers;
        }

        // GET: api/Customers/5
        [ResponseType(typeof(Customer))]
        public IHttpActionResult GetCustomer(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return NotFound();
            }

            return Ok(customer);
        }

        // PUT: api/Customers/5
        [ResponseType(typeof(void))]
        public IHttpActionResult PutCustomer(int id, Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != customer.CustId)
            {
                return BadRequest();
            }

            db.Entry(customer).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CustomerExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/Customers
        [ResponseType(typeof(Customer))]
        public IHttpActionResult PostCustomer(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Customers.Add(customer);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", 
                                   new { id = customer.CustId }, customer);
        }

        // DELETE: api/Customers/5
        [ResponseType(typeof(Customer))]
        public IHttpActionResult DeleteCustomer(int id)
        {
            Customer customer = db.Customers.Find(id);
            if (customer == null)
            {
                return NotFound();
            }

            db.Customers.Remove(customer);
            db.SaveChanges();

            return Ok(customer);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool CustomerExists(int id)
        {
            return db.Customers.Count(e => e.CustId == id) > 0;
        }
    }
API Context Class

After adding the scaffold controller the API context class is also created inside the Model folder like below, that should contains the context of database schema. Here you can see CustomerAPIContext class implement the DbContext and base(“name=CustomerAPIContext”) is the name of the connection string to communicate with DB.

public class CustomerAPIContext : DbContext
    {
        public CustomerAPIContext() : base("name=CustomerAPIContext")
        {
        }
        public System.Data.Entity.DbSet<CustomerAPI.Models.Customer> 
                       Customers { get; set; }
    }

Entity Framework Code First Migrations

Code first migrations here help you to update the existing database with your newly added model classes and your existing database remains intact with the existing data.

  • Open Package manager console of the API project and type the command Enable-Migrations and hit enter.

After adding this command a Migrations folder is generated like blow with crating the Configuration.cs class. This class is derived from DbMigrationsConfiguration class. This class contains a Seed method having the parameter as the context class that we got generated in the Models Seed is an overridden method that means it contains a virtual method in a base class and a class driven from DbMigrationsConfiguration can override that and add custom functionality.

internal sealed class Configuration : DbMigrationsConfiguration<CustomerAPI.Models.CustomerAPIContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
    }
The next step is to execute the command named “Add-Migrations”. In the package manager console. The command would be Add-Migrations Initial “Initial” is the parameter we have use, you may be use any other text as per your choice.

After executing the command it adds a new file with the name “Initial” prefixed with the date time stamp. It prefixes the date time stamp so that it could track the various migrations added during development and segregate between those. Open the file and we see the class named “Initial” deriving from DbMigration class. This class contains two methods that are overridden from DbMigration class i.e. the base class. The method names are Up() and Down().

The Up method is executed to add all the initial configuration to the database and contains the create command in LINQ format. This helps to generate tables and all the modifications done over the model. Down command is the opposite of Up command. The code in the file is self-explanatory. The Up command here is having the code that creates the Students table and setting Id as its primary key. All this information is derived from the model and its changes.

  • The final command that creates the database and respective tables out of our context and model. It executes the Initial migration that we added and then runs the seed method from the configuration class. This command is smart enough to detect which migrations to run. For example it will not run previously executed migrations and all the newly added migrations each time will be taken in to account to be executed to update the database. It maintains this track as the database firstly created contains an additional table named __MigrationHistory that keeps track of all the migrations done.
  • The command is Update-Database
  • After the command execution, it creates the database in the specified server as per your server and adds the corresponding connection string to the Web.Config file. The name of the connection string is the same as the name of our context class and that’s how the context class and connection strings are related.
<connectionStrings>
    <add name="CustomerAPIContext" connectionString="Data Source=ServerName; Initial Catalog=customers; User ID=sa;password=*****;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Now it automatically create the database named as “customers” with table name “customer”. Also it holds the migration history in the tables.

Exploring the Generated Database

You can see when navigate to SQL Server, find their the database is created for us.

But there is may be issue to access the Web API due to CORS. Let’s understand CORS

What is CORS and how & why to enable CORS in ASP.NET Web API ?

CORS (Cross-Origin Resource Sharing) : cross-origin HTTP request occurs when it requests a resource from a different domain, protocol, or port than the one from which the current document originated.

In this application, our web API project will block request from angular application, since they are cross-origin HTTP request(from different port numbers – 4200 and 49243). In-order to allow cross-origin HTTP request, we have to configure Web API project for this localhost:4200 request. so let’s look how we can do that.

How to enable CORS in ASP.NET Web API Project
  • To enable CORS in ASP.NET Web API Project add the below package in ASP.NET Web API application. To add this package you can select the project then on Nuget package search CORS and install this.

Also you can install this package using Nuget package manager console using below command

Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.2.3
  • Then to enable the CORS add the below code inside WebApiConfig.cs file, present in App_start folder.
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();
            var cors = new EnableCorsAttribute("*", "*", "*");
            //origins,headers,methods   
            config.EnableCors(cors);
        }
    }

Now the ASP.NET Web API project project is complete, let’s create an Angular 10 application and consume the Web API inside the angular application.

Create Angular 10 Application

To create angular application we use Visual studio code editor. You can choose any editor using Angular CLI.

Creating new angular application

To create the Angular application with name NgCustomerCRUD and install default packages from npm, you can use following command.

ng new NgCustomerCRUD

Add Required Angular CRUD Components

Add the below CRUD Components using below command.

# from root component
   ng g c customers
# switch to parent component directory
   cd src\app\customers
# create child components
   ng g c customer
   ng g c customer-list

we creates customers component, remaining two components will be child components for this customers component. following command creates child components customer and customer-list components.

Open appmodule.ts file, Make sure that newly added components are added to declarations array.

import { CustomersComponent } from './customers/customers.component';
import { CustomerComponent } from './customers/customer/customer.component';
import { CustomerListComponent } from './customers/customer-list/customer-list.component';
import { ToastrModule } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  declarations: [
    AppComponent,
    CustomersComponent,
    CustomerComponent,
    CustomerListComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    BrowserAnimationsModule,
    ToastrModule.forRoot()
  ],

Angular 10 Project Structure

The below are the project structure of Angular application of the Customer CRUD application. On the below we use

On the src/app folder we create the root component name as “Customers” along with html and css files.
Then add the customer form component inside the Customers folder.
Then add the customer-list component to view the customer data and in their we should create the Edit & Delete.
Under the shared folder we add the service class name as “customer.service.ts” to call the Web API and a model class is create name as “customer.model.ts” that hold the customer object.
And, finally add all the components info into the app.model.ts file and add the CDN file for style or you can install these file manually and add it into angular.json file.

● src
+---● app
|   +--● customers (the root component)
|   |  |--customers.component.ts|.html|.css
|   |  +--● customer (customer form)
|   |  |  |--customer.component.ts|.html|.css
|   |  |
|   |  +--● customer-list (list inserted customers)
|   |  |  |--customer-list.component.ts|.html|.css
|   |  |
|   |  +--● shared
|   |     |--customer.service.ts
|   |     |--customer.model.ts
|   |
|   |--app.module.ts
|
+---● environments
|   |--environment.ts
|
|--index.html (cdn path for bootstrap and font awesome icon)

Create Service and Model Class

To create these classes let’s add a new folder sharedinside customers folder (/src/app/customers/ ).

Now create customer model class

# switch to shared folder
cd src\app\customers\shared
# create customer model class
ng g class customer --type=model
# create customer service class
ng g s customer

Let’s create the customer model class with following properties. CustId is the property that hold each record individually.

export class Customer {
    CustId:number;
    Name:string;
    Address:string;
    Mobile:string;
    Email:string;
}

Create Service Class to consume ASP.NET Web API, the service name is customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, Subject } from 'rxjs';
import { Customer } from './customer.model';
const baseURL = 'http://localhost:49243/api/Customers';
@Injectable({
  providedIn: 'root'
})
export class CustomerService {
  selectedCustomer : Customer;
  CustomerList : Observable<Customer[]>;

  constructor(private httpClient: HttpClient) {
   }
  getCustomerList(): Observable<Customer[]> {  
    this.CustomerList=this.httpClient.get<Customer[]>(baseURL);  
    return this.CustomerList;  
  }  
  getCustomerById(id): Observable<any> {
    return this.httpClient.get(`${baseURL}/${id}`);
  }
  addCustomer(data): Observable<any> {
    return this.httpClient.post(baseURL, data);
  }
  updateCustomer(id, data): Observable<any> {
    return this.httpClient.put(`${baseURL}/${id}`, data);
  }
  deleteCustomer(id): Observable<any> {
    return this.httpClient.delete(`${baseURL}/${id}`);
  }
  deleteAllCustomer(): Observable<any> {
    return this.httpClient.delete(baseURL);
  }
  searchByCustomer(name): Observable<any> {
    return this.httpClient.get(`${baseURL}?name=${name}`);
  }
}
  • In this service class we have imported http and rxjs related classes. http class is used to consume the Web API methods for Insert Update and Delete operations.
  • The model class customer.model.ts is inject into service class.
  • baseURL = ‘http://localhost:49243/api/Customers’ is the URL of ASP.NET Web API to consume the service.
  • selectedCustomer is the variable that hold the customer model class.
  • CustomerList is contains the Observable<Customer[]>.
  • getCustomerList to fetch all the customer information and getCustomerById(id) fetch the customer information by Id.
  • addCustomer and updateCustomer method service use for customer information add and update the data.
  • deleteCustomer and searchByCustomer accordingly use to do the CRUD operation.

Design the CRUD Customer Template

We use bootstrap and font-Awesome Icons For Application Design. So first of all add CDN reference for these style sheets inside index.html. You can also add the package and use it.
  <!-- Bootstrap -->
<link rel="preload" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" data-rocket-async="style" as="style" onload="this.onload=null;this.rel='stylesheet'" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<!-- font-awesome -->
<link rel="preload" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" data-rocket-async="style" as="style" onload="this.onload=null;this.rel='stylesheet'">
Update add the selector <app-customers> app.component.html as follows

<div class="container">
  <app-customers></app-customers>
</div>
Add the following selector inside the customers.component.html file.

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Customer Angular CRUD using ASP.NET Web API</a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" 
         data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" 
                    aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
  </nav>
  <div class="row mt-2">
    <div class="col-md-6">
      <app-customer></app-customer>
    </div>
    <div class="col-md-6">
      <app-customer-list></app-customer-list>
    </div>
  </div>

Angular CRUD Operations Form

we’ll create a customer form to implement Insert and Update Operation with customer Component. So we are going to create a Template Driven Form(TDF) using selectedCustomer property from injected CustomerService Class.

Insert Update  and Reset Operation

Let’s discuss how to add the customer component with TS file and html.

customer.component.html

<form class="cust-form" #customerForm="ngForm" (ngSubmit)="onSubmit(customerForm)">
    <input type="hidden" name="CustId" #CustId="ngModel" [(ngModel)]="custservice.selectedCustomer.CustId">
   
      <div class="form-group  col-md-8">
        <input class="form-control" name="Name" #Name="ngModel" [(ngModel)]="custservice.selectedCustomer.Name"
          placeholder=" Name" required>
        <div class="validation-error" *ngIf="Name.invalid && Name.touched" style="color: red;">This Field is Required.</div>
      </div>
    
    <div class="form-group col-md-8">
      <input class="form-control" name="Address" #Address="ngModel" [(ngModel)]="custservice.selectedCustomer.Address" placeholder="Address"
        required>
      <div class="validation-error" *ngIf="Address.invalid && Address.touched" style="color: red;">This Field is Required.</div>
    </div>

    <div class="form-group col-md-8">
      <input class="form-control" name="Mobile" #Mobile="ngModel" [(ngModel)]="custservice.selectedCustomer.Mobile" 
         placeholder="Mobile" required>
      <div class="validation-error" *ngIf="Mobile.invalid && Mobile.touched" style="color: red;">This Field is Required.</div>
    </div>
   
      <div class="form-group col-md-8">
        <input class="form-control" name="Email" #Email="ngModel" [(ngModel)]="custservice.selectedCustomer.Email" 
         placeholder="Email" required>
        <div class="validation-error" *ngIf="Email.invalid && Email.touched" style="color: red;">This Field is Required.</div>
      </div>
      <div class="row ml-1">
      <div class="form-group col-md-4">
        <button [disabled]="!customerForm.valid" type="submit" class="btn btn-lg btn-block btn-primary">
          <i class="fa fa-floppy-o"></i> Submit</button>
      </div>
      <div class="form-group col-md-4">
        <button type="button" class="btn btn-lg btn-block btn-default" (click)="resetForm(customerForm)">
          <i class="fa fa-repeat"></i> Reset</button>
      </div>
    </div>
  </form>
  • A hidden field is added for CustId property.
  • custservice.selectedCustomer is to add the field like Name, Address, Email and Mobile.
  • required attribute is added to Name and Address, Email and Mobile text boxes, so these two fields are mandatory to submit this form. When these text-boxes are invalid, ng-invalid and ng-dirty class will automatically added to it. so based on these classes we have implemented form validation. When these text boxes are not valid, customer form as whole is not valid, so we added conditional disable attribute to Submit Button.

when these text boxes are not valid, customer form as whole is not valid, so we added conditional disable attribute to Submit Button.

<button [disabled]="!customerForm.valid" type="submit" class="btn btn-lg btn-block btn-primary">
          <i class="fa fa-floppy-o"></i> Submit</button>
customer.component.ts

import { Component, OnInit } from '@angular/core';
import { NgForm } from '@angular/forms'
import { CustomerService } from '../shared/customer.service'
import { ToastrService } from 'ngx-toastr'
@Component({
  selector: 'app-customer',
  templateUrl: './customer.component.html',
  styleUrls: ['./customer.component.css']
 
})
export class CustomerComponent implements OnInit {
  custIdUpdate = null;  
  constructor(public custservice: CustomerService, private toastr: ToastrService) {
   
  }
  ngOnInit(): void {
    this.resetForm();
  }
  resetForm(form?: NgForm) {
    if (form != null)
      form.reset();
    this.custservice.selectedCustomer = {
      CustId: 0,
      Name: '',
      Address: '',
      Mobile: '',
      Email: ''
    }
  }

  onSubmit(form: NgForm) {
    console.log(form.value.CustId);
    if(form.value.CustId==null)
    {
      form.value.CustId=0;
    }
    this.custservice.selectedCustomer.CustId=form.value.CustId
    if (this.custservice.selectedCustomer.CustId == 0) {
      this.custservice.addCustomer(form.value)
        .subscribe(data => {
          form.value.CustId=0;
          this.resetForm(form);
          this.custservice.getCustomerList();
          this.toastr.success('New Record Added Succcessfully', 'Customer Registration');
        })
    }
    else {
      console.log("hello");
      this.custservice.updateCustomer(form.value.CustId, form.value)
      .subscribe(data => {
        this.resetForm(form);
        this.custservice.getCustomerList();
        this.toastr.info('Record Updated Successfully!', 'Customer Registration');
      });
    }
  }
}
  • Inside customer.component.ts file we write code for Insert, Update and Delete Operation.
  • Inject the CustomerService and ToastrService in the customer component.
  • Then on Submit form add the customer form. If the customer Id is null then it insert the data using call the service method else it update the record.
  • restForm function is used reset form controls value to initial stage, we called this function from reset button click event and from ngOnint  Lifecycle Hook to initialize the form.
  • Inside the form submit event function OnSubmit, we implement both insert and update operation based on CustomerID value. To show the success message,  we use ToastrService class object toastr.

Install package ngx-toastr

Before that we are going to install ngx-toastr from npm package. This package helps us to show notification message inside angular applications.

To install ngx-toastr follow the below command.

npm install ngx-toastr --save

Then add ToastrModule inside appmodule.ts file.

import { ToastrModule } from 'ngx-toastr';
@NgModule({
  declarations: [
  ],
  imports: [
      ToastrModule.forRoot()
  ],

Then add toastr.css style-sheet reference in .angular-cli.json file.

 "styles": [
              "src/styles.css",
              "node_modules/ngx-toastr/toastr.css"
            ],

Run application and you see the customer design form look like below. You can run the application using below command.

ng s --o

List Inserted Records and Delete Operation

Using customer-list component we add the list of all inserted customers and implement Delete operation. You can add following inside customer-list component.

customer-list.component.ts

import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr'
import { Customer } from '../shared/customer.model';
import { CustomerService } from '../shared/customer.service';
import { Observable, of, Subject } from 'rxjs';
@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
  allCustomers: Observable<Customer[]>;  

  constructor(public custservice: CustomerService,
                       private toastr : ToastrService) { }
  ngOnInit() {
    this.loadAllCustomers();  
  }
  loadAllCustomers() {  
    this.allCustomers = this.custservice.getCustomerList();  
  }  

  getCustomerList() {  
   this.custservice.getCustomerList();  
  }  
  showForEdit(cust: Customer) {
    this.custservice.selectedCustomer = Object.assign({}, cust);;
  }

  onDelete(id: number) {
    if (confirm('Are you sure to delete this record ?') == true) {
      this.custservice.deleteCustomer(id)
      .subscribe(x => {
        this.custservice.getCustomerList();
        this.toastr.warning("Deleted Successfully","Employee Register");
      })
    }
  }
}
  • Inside the customer-list.componenet.ts we have injected CustomerService and ToastrService Class.
  • Inside the ngOnint  Lifecycle hook, we called loadAllCustomers from CustomerService class. It will store customer collection from customer table inside customerList array. Now we can use this array to list customer collection.
customer-list.component.html

<table class="table table-sm table-hover">
    <tr *ngFor="let customer of custservice.CustomerList | async">
      <td>{{customer.Name}}</td>
      <td>{{customer.CustId}}</td>
      <td>
        <a class="btn" (click)="showForEdit(customer)">
          <i class="fa fa-pencil-square-o"></i>
        </a>
        <a class="btn text-danger" (click)="onDelete(customer.CustId)">
          <i class="fa fa-trash-o"></i>
        </a>
      </td>
    </tr>
  </table>
  • On the above we iterate the customer list bind when submit the record.
  • Also we use Edit and Delete operation with using method showForEdit() and onDelete()

Run the application again and the component design looks like this

  • When we click on pencil button it will call showForEdit function to populate corresponding record inside the customer form.
  • Using trash icon we implemented delete operation with onDelete function.

Final CRUD operation output

Let’s run the application and see the Final output of CRUD operation using Angular with ASP.NET Web API.

Source Code

Find the source code on the link.

Summary

This article explain Angular 10 application CRUD Operation using ASP .NET Web API. In this article we discuss how to create ASP .NET Web API project and how to consume the API inside in angular 10 application. In this example we use

  • ASP .NET Web API with Entity Framework code-first-approach
  • Angular 10 application with CRUD operation with Toastr message.

That’s a wrap for this article. I hope that it cleared about Angular 10 CRUD operations. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Related Post

CRUD Operation in ASP.NET Web API with Entity Framework
CRUD-Operation-in-asp.net-Web-api

This blog explain CRUD Operation in ASP.NET Web API with Entity framework and then the web API check using POSTMAN Read more

How to create custom pipes in Angular
How to create custom pipes in Angular

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are Read more

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

How to create custom pipes in Angular

How to create custom pipes in Angular

In this article we are going to discuss how to create custom pipes in Angular. If you are new to Angular then please explore our angular series in the link. Let’s first discuss what is a Pipe in angular.

What is a Pipe in Angular ?

Every application runs doing a simple task : get data, transform them, and show them to users. Introducing Angular pipes, a way to write display-value transformations that you can declare in your HTML.

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are used for data transformations in an Angular application.

Built-in Pipes Provided by Angular

  • CurrencyPipe
  • DatePipe
  • DecimalPipe
  • JsonPipe
  • LowerCasePipe
  • UpperCasePipe
  • PercentPipe
  • SlicePipe
  • AsyncPipe etc..

To check all built-in pipes provided by angular please explore our angular series in this link.

Create a Custom Pipe in Angular

We take a example of how a description box have a minimal filed using custom pipes. Let’s say a description text is about 500 characters but you want to show it only 50 chars. and on tool tip you may show all the characters.

Let’s create a Angular 9 application using Visual Studio Code.

  • Open the VS Code
  • Open the VS Code Terminal Window
  • Add the below command to create a new project
Angular NewProject
CoreSpider– Angular New Project with routing Yes and style as css

After creation of the project then move into the project folder using below command.

cd ng-custom-pipe

Create a new component named as “product” using below command

ng g c product
Product Component
Product Component

Open the Product.ts file add the dummy product information like this.

After adding the product component, it automatically add in the module.ts in the root folder.

Product Component in module.ts
Product Component in module.ts

Then remove all the predefined HTML body content in app.component.html.

Component in router outlet
Product Component in router outlet

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

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  products: any[];
  constructor() {
    this.products = [
      { id: '001', name: 'Laptop', model: 'HP-Pavilion', price: 62000, quantity: 1,
                description: 'HP Pavilion 15 is a Windows 10 laptop with a 15.60-inch display that has a resolution of 1366x768 pixels. It is powered by a Core i7 processor and it comes with 8GB of RAM. The HP Pavilion 15 packs 1TB of HDD storage. Graphics are powered by Nvidia GeForce 940MX'},
      { id: '002', name: 'Mobile', model: 'Samsung-Note10', price: 125000, quantity: 2,
                description: 'Samsung Galaxy Note 10 is powered by a 1.9GHz octa-core Samsung Exynos 9825 processor that features 4 cores clocked at 1.9GHz, 2 cores clocked at 2.4GHz and 2 cores clocked at 2.7GHz. It comes with 8GB of RAM. The Samsung Galaxy Note 10 runs Android 9 Pie and is powered by a 3500mAh battery.'}
    ];
  }

  ngOnInit(): void {
  }

}

<h2>Product Information</h2>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Model</th>
            <th>Price</th>
            <th>Quantity</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let prod of products'>
            <td>{{prod.id}}</td>
            <td>{{prod.name}}</td>
            <td>{{prod.model}}</td>
            <td>{{prod.price}}</td>
            <td>{{prod.quantity}}</td>
            <td>{{prod.description}}</td>
        </tr>
        <tr *ngIf="!products || products.length==0">
            <td colspan="7">
                No Products to display
            </td>
        </tr>
    </tbody>
  </table>

Run the application and you can see the output like below; You can see the description is printed here with full text characters.

custom pipes in Angular-datashow
CoreSpider– Product output

How to use Custom Pipes

Let’s introduce with custom pipes and do the description with minimal characters. Let’s create a new folder named as “CustomPipe” and add a angular pipe using below command.

ng g pipe custom-text-length
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customTextLength'
})
export class CustomTextLengthPipe implements PipeTransform {

  transform(value: string, limit?: number) {
    if (!value)
    {
      return null;
    }
    const actuallimit = (limit) ? limit : 75;
    return value.substr(0, actuallimit) + '......';
  }
}

Code Explanation

We create the custom pipe named as customTextLength and here you can see we add the limit text as 75 characters that means when we add this custom pipe into angular interpolation it limit the filed.

custom pipes in Angular-custom pipe dynamic description
https://corespider.com/ – Custom Pipe add

Let’s run the application and see the description field now is limited to 75 characters and on tool tip you can see full text.

custom pipes in Angular-output
CoreSpider– Custom pipe output

Summary

This article explain how to create custom pipes. if have any suggestion then please give your feedback.

That’s a wrap for this article. I hope that it cleared about How to create custom pipes in Angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

Angular 10 with ASP.NET Web API-CRUD Operations
Angular-10-with-ASP.NET-Web-API-CRUD-Operations

Angular CRUD operation using ASP .NET Web API with Entity Framework Code first approach in SQL Server. Beginners guide to Read more

How to use angular material in angular

How to use angular material in angular

In this article we are going to discuss how to use angular material in angular 9 application. If you are new to angular then explore our Angular Series. If you miss our previous article of angular Routing then please follow the link.

Let’s Create sample angular 9 application and there we use material design. We have create some controls of materiel theme in this example. To create angular 9 application use the below command.

Create Angular Project

The below command is use if are freshly start the angular and install updated angular CLI version.

npm install -g @angular/cli@

To create a new project add the below command with Routing as YES and style as CSS. ng-material-design here our project name, you can create a project according to your choice.

ng new ng-material-design

Add the material design into angular

Using below command we can add the material design into angular 9 application.

ng add @angular/material
install material design in angular 9

On the above image while we run the command it prompt that which material theme want to install. In our case we use “Indigo/Pink”. You can install any other theme according to your choice just navigate to the themes.

material theme

On the above image you can see after installing the “Indigo/pink” theme the material package also added into package.json, angualr.json and styles.css automatically.

After adding the theme you can find the css in angular.json file like below;

"styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "src/styles.css"
            ],

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import {MatSliderModule} from '@angular/material/slider';
import {MatSelectModule} from '@angular/material/select';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSliderModule,
    FormsModule,
    MatButtonModule,
    MatIconModule,
    MatSelectModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Code Explanation

We need to add the several modules into app.module.ts to access in HTML page. After importing the module we need to add into Imports[].

Remove all the predefined HTML in app.componenet.html file then add the materiel design like below;

<div class="container mt-5">
  <h1>Angular Basic Material Design form</h1>
  <h2>Slider</h2>
  <mat-slider min="1" max="100" step="1" value="1"></mat-slider>
  <h2>TextBox</h2>
   <input matInput placeholder="Simple Input" [(ngModel)]="title" class="form-control">
   <h2>Dropdown</h2>
   <mat-form-field appearance="fill">
    <mat-label>Favorite food</mat-label>
    <mat-select>
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
  </mat-form-field>
  <h2>Icon</h2>
  <mat-icon>home</mat-icon>
  <h2>Button</h2>
  <button mat-raised-button>Material button</button>
</div>

import { Component } from '@angular/core';

interface Food {
  value: string;
  viewValue: string;
}
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-material-design';
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
}

Code Explanation

app.component.html

  • Here we take a basic example to create a materiel text box. Matinput is responsible for to convert the textbox into material text-box with [(ngModel)] is used to bind the title.
  • Then we create the material slider, Icon, Button etc..
  • We create a dummy drop down to access the value from app.component.ts. In the mat-option we iterate the result and bind the data into dropdown.

app.component.ts

  • Here we declare title value that should append on the text box.
  • Then we added a Interface of Food that hold the fruits information.
  • Finally, we declare a foods list that contain food array.
  • Consuming the foods list the drop-down can bind.

That’s it run the application and see the output like below;

Summary

So far this article we discuss how to use material design in angular 9. If have any suggestion about this article please give your feedback.

That’s a wrap for this article. I hope that it cleared about How to use angular material in angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

Angular 10 with ASP.NET Web API-CRUD Operations
Angular-10-with-ASP.NET-Web-API-CRUD-Operations

Angular CRUD operation using ASP .NET Web API with Entity Framework Code first approach in SQL Server. Beginners guide to Read more

How to create custom pipes in Angular
How to create custom pipes in Angular

A pipe takes in data as input and transforms it to a desired output. Simply you can say Pipes are Read more

Pin It on Pinterest