How to Create Nested Grid using Angular 8

Introduction

 
In this article, we will learn how we create a nested grid in Angular 8.
 

How it works

 
We are using the grid list to separate the page into small sections. In each section, we want to place a different component, where one of these components is another smaller grid.
 
Prerequisite
  • Basic knowledge of Angular
  • Visual Studio Code must be installed
  • Angular CLI must be installed
  • Node JS must be installed 

FRONTEND

 
Step 1
 
Let's create an Angular project using following npm command
  1. ng new nestedGrid   
Step 2
 
Open the newly created project in Visual Studio code and install bootstrap in this project 
  1. npm install bootstrap --save  
Now open styles.css file and add Bootstrap file reference. To add a reference in styles.css file, add this line:
  1. @import '~bootstrap/dist/css/bootstrap.min.css';  
Step 3
 
Now, let's create a new component by using the following command.
  1. ng g c product  
Step 4
 
Now create a new service using the following command.
  1. ng generate service product  
Step 5
 
Now, open the 'product.component.html' and paste the following code to see the HTML template. 
  1. <div class="card">  
  2.   <div class="card-body pb-0">  
  3.     <h4 style="text-align: center;">Example of Angular Nested Grid</h4>  
  4.     <div class="row">  
  5.       <div class="col-12 col-md-12">  
  6.         <div class="card">  
  7.   
  8.           <div class="card-body position-relative">  
  9.             <div class="table-responsive cnstr-record product-tbl">  
  10.               <table class="table table-bordered heading-hvr">  
  11.                 <thead>  
  12.                   <tr>  
  13.                     <th> </th>  
  14.                     <th width="50">Art.No  
  15.                     </th>  
  16.                     <th>Brand</th>  
  17.                     <th>  
  18.                       Price/Unit</th>  
  19.                     <th>Provider</th>  
  20.                     <th>P. Art. N</th>  
  21.                     <th>S. A/C</th>  
  22.                     <th>Buy A/C</th>  
  23.                   </tr>  
  24.                 </thead>  
  25.   
  26.                 <tbody *ngFor="let product of products; let i = index">  
  27.   
  28.                   <tr>  
  29.                     <td align="center">  
  30.                       <a class="expand-row" *ngIf="!hideme[i]" (click)="showProductCountryInfo(i,product.ProductId)">  
  31.                         <img src="../../assets/Images/plus.png" />  
  32.   
  33.                       </a>  
  34.                       <a class="expand-row" *ngIf="hideme[i]" (click)="hideme[i] = !hideme[i]">  
  35.                         <img src="../../assets/Images/minus.png" />  
  36.                       </a>  
  37.                     </td>  
  38.                     <td align="center">{{product.ArtNo}}</td>  
  39.                     <td>{{product.Brand}}</td>  
  40.                     <td>{{product.Price }}</td>  
  41.                     <td>{{product.Provider}}</td>  
  42.                     <td>{{product.ProviderArtNo}}</td>  
  43.                     <td>{{product.SalesAccount}}</td>  
  44.                     <td>{{product.BuyAccount}}</td>  
  45.                   </tr>  
  46.   
  47.                   <!-- <div id="myresult" class="img-zoom-result"></div> -->  
  48.                   <tr [hidden]="!hideme[i]" class="sub-table no-bg">  
  49.                     <td align="center"> </td>  
  50.                     <td colspan="15" class="p-0">  
  51.                       <table class="table mb-0 table-striped">  
  52.                         <thead class="bg-dark text-white">  
  53.                           <tr>  
  54.                             <th>CountryName</th>  
  55.                             <th>Price/Unit</th>  
  56.                             <th>Sales Account</th>  
  57.                             <th>Buy Account</th>  
  58.                               
  59.                           </tr>  
  60.                         </thead>  
  61.                         <tbody>  
  62.                           <tr *ngFor="let productCountryInfo of productCountryInformation[i]">  
  63.                             <td>{{productCountryInfo.CountryName}}</td>  
  64.                             <td>{{productCountryInfo.Price}}</td>  
  65.                             <td>{{productCountryInfo.SalesAccount}}</td>  
  66.                             <td>{{productCountryInfo.BuyAccount}}</td>  
  67.                              
  68.                           </tr>  
  69.                         </tbody>  
  70.                       </table>  
  71.                     </td>  
  72.                   </tr>  
  73.   
  74.                 </tbody>  
  75.               </table>  
  76.             </div>  
  77.           </div>  
  78.         </div>  
  79.       </div>  
  80.     </div>  
  81.   </div>  
  82. </div>   
Step 6
 
After then open 'product.component.ts' file and add the following code in this file where our logic has been written.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ProductsService } from './products.service';  
  3.   
  4. @Component({  
  5.   selector: 'app-products',  
  6.   templateUrl: './products.component.html',  
  7.   styleUrls: ['./products.component.css']  
  8. })  
  9. export class ProductsComponent implements OnInit {  
  10.   
  11.   products = [];  
  12.   countryCode: any;  
  13.   currencySymbol:any;  
  14.   productCountryInformation: any = [];  
  15.   hideme = [];  
  16.   Index: any;  
  17.   countryId: any;  
  18.   country: any;  
  19.   priceToDisplay=[];  
  20.   
  21.    constructor(private _productService: ProductsService) {  
  22.   }  
  23.   ngOnInit() {  
  24.   
  25.     this.countryId=0;  
  26.     this.getProducts(this.countryId);  
  27.   }  
  28.   
  29.   public getProducts(countryId) {  
  30.     let data = [];  
  31.     this._productService.getAllProducts(countryId).subscribe((data: any) => {  
  32.       this.products =data;  
  33.         
  34.     })  
  35.   
  36.   }  
  37.   public showProductCountryInfo(index,productId) {  
  38.     this._productService.countryInfo(productId).subscribe((res:any)=>{  
  39.       this.productCountryInformation[index] = res;  
  40.     })  
  41.     this.hideme[index] = !this.hideme[index];  
  42.     this.Index = index;  
  43.   }  
  44.   
  45. }  
Step 7
 
Next open 'product.component.css' file and paste the code for styling.
  1. @charset "utf-8";   
  2. /* CSS Document */  
  3. @media all{  
  4.     *{padding:0px;margin:0px;}  
  5. div{vertical-align:top;}  
  6. img{max-width:100%;}  
  7. html {-webkit-font-smoothing:antialiased; -moz-osx-font-smoothing:grayscale;}  
  8. body{overflow:auto!importantwidth:100%!important;}  
  9. html, body{background-color:#e4e5e6;}  
  10. html {position:relativemin-height:100%;}  
  11.   
  12.   
  13. .card{border-radius:4px;}  
  14. .card-header:first-child {border-radius:4px 4px 0px 0px;}  
  15.   
  16. /*Typekit*/  
  17. html, body{font-family:'Roboto'sans-seriffont-weight:400font-size:13px;}  
  18. body{padding-top:52px;}  
  19.   
  20. p{font-family:'Roboto'sans-serifcolor:#303030font-weight:400margin-bottom:1rem;}  
  21. input, textarea, select{font-family:'Roboto'sans-serif;}  
  22.   
  23. h1,h2,h3,h4,h5,h6{font-family:'Roboto'sans-seriffont-weight:700;}  
  24. h1{font-size:20pxcolor:#000000margin-bottom:10px;}  
  25. h2{font-size:30px;}  
  26. h3{font-size:24px;}  
  27. h4{font-size:18px;}  
  28. h5{font-size:14px;}  
  29. h6{font-size:12px;}  
  30.   
  31. .row {margin-right:-8pxmargin-left:-8px;}  
  32. .col, .col-1, .col-10, .col-11, .col-12, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-auto, .col-lg, .col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-auto, .col-md, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-auto, .col-sm, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-auto, .col-xl, .col-xl-1, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-auto {padding-right:8pxpadding-left:8px;}  
  33.   
  34. .card-header{background-color:#f0f3f5border-bottom:1px solid #c8ced3font-size:13pxfont-weight:600color:#464646text-transform:uppercasepadding:.75rem 8px;}  
  35.   
  36.   
  37. .cnstr-record th{white-space:nowrap;padding:.45rem .2rem; font-size:13pxborder-bottom-width:0px!important;}  
  38. .cnstr-record thead{background:#f0f3f5;}  
  39.   
  40. .cnstr-record .form-control{font-size:13pxpadding:0px 0rem 0px 0.2rem; height:calc(2rem + 2px);}  
  41. .cnstr-record select.form-control{padding-left:.05rem;}  
  42. .cnstr-record .table td, .cnstr-record .table th {vertical-align:middle;}  
  43. .cnstr-record .table td{padding:.3rem;}  
  44. .cnstr-record .table td h4{margin:0px;}  
  45.   
  46. .wp-50{width:50px;}  
  47. .wp-60{width:60px;}  
  48. .wp-70{width:70px;}  
  49. .wp-80{width:80px;}  
  50. .wp-90{width:90px;}  
  51. .wp-100{width:100px;}  
  52. .mw-auto{min-width:inherit;}  
  53. .expand-row{width:100%border:solid 1px #596269display:inline-block; border-radius:3pxwidth:16pxheight:16pxvertical-align:topbackground:#596269color:#ffffff!important;}  
  54. .expand-row img{vertical-align:topposition:relative; top:2px;}  
  55. .sub-table th{font-weight:400font-size:12px;}  
  56. .sub-table td{background:#efefef;}  
  57. .no-bg td{background:inherit;}  
  58. .mw-100{max-width:100%;}  
  59.   
  60. }   
Step 8
 
At last, open 'product.service.ts' file and add services to call our API.
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient } from '@angular/common/http';  
  3.   
  4.   
  5. @Injectable()  
  6.   
  7.   
  8. export class ProductsService {  
  9.   
  10.     private url = ""
  11.   
  12.     constructor(public http: HttpClient) {  
  13.     }  
  14.   
  15.     getAllProducts(countryCode) {  
  16.         this.url = 'http://localhost:49661/api/Company/getAllProducts?countryCode='+countryCode;  
  17.         return this.http.get<any[]>(this.url);  
  18.     }  
  19.      
  20.     countryInfo(productId) {  
  21.         this.url = 'http://localhost:49661/api/Company/getProductCountryInformation?productId='+productId;  
  22.         return this.http.get<any[]>(this.url);  
  23.     }  
  24. }  
Step 9
 
Its time to see the output in your terminal type 'ng serve -o' to compile and open it in browser.
 
After loading our page you can see the output like in the below images:
 
How To Create Nested Grid Using Angular 8 
How To Create Nested Grid Using Angular 8
 
Here, I am taking a product, for example, grid data is related to a product and its corresponding nested grid has information related to their parent grid.
 
You can check a nested grid by clicking the plus icon of parent grid so that you can see the resultant nested grid based on the index, (i.e if you click on very 1st plus icon then you can only see its first product-related information. If you click on second plus icon, then their product-related information would show.)
 
Now, the front end part is done and its time to add server-side code and backend code.
 

WEB API - Create an ASP.NET Core application

 
Follow these steps to create an ASP.NET Core application.
 
Step 1
 
In Visual Studio 2019, click on File -> New -> Project.
 
How To Create Nested Grid Using Angular 8 
 
Step 2
 
Choose the Create option and select Asp.net web application.
 
How To Create Nested Grid Using Angular 8 
 
Step 3
 
Select Web API and click Ok.
 
How To Create Nested Grid Using Angular 8 
 
Step 4
 
Now right click on controller and then add a new item.
 
How To Create Nested Grid Using Angular 8 
 
Step 5
 
Choose Ado.net Entity Data Model and then click on Add.
 
How To Create Nested Grid Using Angular 8 
 
Step 6
 
Next Step is EF Designer, just click on next.
 
How To Create Nested Grid Using Angular 8 
 
Step 7
 
A new pop-up will show. Click on next. If yours isn't established, then click on new connection
 
How To Create Nested Grid Using Angular 8 
 
Step 8
 
Copy your database connection server name and paste it in the server name textbox. You will see all the database, select your database and click on ok. 
 
How To Create Nested Grid Using Angular 8 
 
Step 9
 
The next popup will show, paste your database server name, and choose for the database and test for the connection then click on next. Here, in the new screen, select your tables and store the procedure. Then click on finish.
 
How To Create Nested Grid Using Angular 8
Our next step is to right-click on the controllers folder and add a new controller. Name it as "Product controller" and add the following namespace in the student controller.
 
Here is the complete code for getting all the product data and their nested product information data. 
 
Complete Product controller code 
  1. using System.Linq;  
  2. using System.Web.Http;  
  3. using CompanyDetails.Models;  
  4. namespace CompanyDetails.Controllers  
  5. {  
  6.     [RoutePrefix("api/Company")]  
  7.     public class CompanyController : ApiController  
  8.     {  
  9.         CompanyEntities2 DB = new CompanyEntities2();  
  10.      
  11.         [HttpGet]  
  12.         [Route("getAllCountry")]  
  13.         public object getAllCountry()  
  14.         {  
  15.             return DB.Countries.ToList();  
  16.         }  
  17.   
  18.         [HttpGet]  
  19.         [Route("getAllProducts")]  
  20.         public object getAllProducts(string countrycode)  
  21.         {  
  22.             var productDetails = DB.USP_GetAllProducts().ToList();  
  23.             return productDetails;  
  24.         }  
  25.   
  26.         [HttpGet]  
  27.         [Route("getProductCountryInformation")]  
  28.         public object getProductCountryInformation(int ProductId)  
  29.         {  
  30.             var prod = DB.USP_getCountryInfo(ProductId).ToList();           
  31.             return prod;  
  32.         }  
  33.     }  
  34. }   
Now, its time to enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package.
 
If you are running your frontend application in different port and your server is running in another port, then to avoid a Cross-Origin-Resource-Sharing issue you have to add small code in webapiconfig.cs file.
 
Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
  2. config.EnableCors(cors); 
BACKEND
 
Here Back end related code we will do it using SQL server
 
The very first step is to create a database.
 

Create database

 
Let’s create a database on your local SQL Server. I hope you have installed SQL Server 2017 in your machine (you can use SQL Server 2008, 2012, or 2016, as well).
 
Step 1
 
Create a database product
  1. create database product  
Step 2
 
Create a product table using the following code 
  1. USE [Product]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[Product]    Script Date: 12/18/2019 10:23:19 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[Product](  
  12.     [ProductId] [int] IDENTITY(1,1) NOT NULL,  
  13.     [ProductCountryInformationId] [intNULL,  
  14.     [ArtNo] [nvarchar](50) NULL,  
  15.     [Provider] [nvarchar](50) NULL,  
  16.     [ProviderArtNo] [nvarchar](50) NULL,  
  17.     [Brand] [nvarchar](50) NULL,  
  18.  CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [ProductId] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23. GO  
  24.   
  25. ALTER TABLE [dbo].[Product]  WITH CHECK ADD  CONSTRAINT [FK_Product_ProductCountryInformation] FOREIGN KEY([ProductCountryInformationId])  
  26. REFERENCES [dbo].[ProductCountryInformation] ([ProductCountryInformationId])  
  27. GO  
  28.   
  29. ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_ProductCountryInformation]  
  30. GO  
Make product ID the primary key
 
Step 3
 
Create a product information table using the following code:
  1. USE [Product]  
  2. GO  
  3.   
  4. /****** Object:  Table [dbo].[ProductCountryInformation]    Script Date: 12/18/2019 10:24:02 PM ******/  
  5. SET ANSI_NULLS ON  
  6. GO  
  7.   
  8. SET QUOTED_IDENTIFIER ON  
  9. GO  
  10.   
  11. CREATE TABLE [dbo].[ProductCountryInformation](  
  12.     [ProductCountryInformationId] [intNOT NULL,  
  13.     [Price] [decimal](18, 2) NULL,  
  14.     [BuyAccount] [nvarchar](50) NULL,  
  15.     [SalesAccount] [nvarchar](50) NULL,  
  16.     [CountryName] [nvarchar](50) NULL,  
  17.     [ProductId] [intNULL,  
  18.  CONSTRAINT [PK_ProductCountryInformation] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [ProductCountryInformationId] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23. GO  
  24.   
  25. ALTER TABLE [dbo].[ProductCountryInformation]  WITH CHECK ADD  CONSTRAINT [FK_ProductCountryInformation_Product] FOREIGN KEY([ProductId])  
  26. REFERENCES [dbo].[Product] ([ProductId])  
  27. GO  
  28.   
  29. ALTER TABLE [dbo].[ProductCountryInformation] CHECK CONSTRAINT [FK_ProductCountryInformation_Product]  
  30. GO  
  31.   
  32. ALTER TABLE [dbo].[ProductCountryInformation]  WITH CHECK ADD  CONSTRAINT [FK_ProductCountryInformation_ProductCountryInformation] FOREIGN KEY([ProductCountryInformationId])  
  33. REFERENCES [dbo].[ProductCountryInformation] ([ProductCountryInformationId])  
  34. GO  
  35.   
  36. ALTER TABLE [dbo].[ProductCountryInformation] CHECK CONSTRAINT [FK_ProductCountryInformation_ProductCountryInformation]  
  37. GO   
Now its time to add some store procedures
 
Step 4
 
All you have to do is paste the following code in a new query:
  1. USE [Product]  
  2. GO  
  3. /****** Object:  StoredProcedure [dbo].[USP_GetAllProducts]    Script Date: 12/18/2019 10:24:35 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. ALTER Proc [dbo].[USP_GetAllProducts]  
  9. As  
  10. Begin  
  11.     Select  p.*,pci.Price,pci.BuyAccount,pci.SalesAccount from [Product] p    
  12.   left join [ProductCountryInformation] pci    
  13.   on p.ProductCountryInformationId=pci.ProductCountryInformationId   
  14. End  
  15.   
  1. USE [Product]    
  2. GO    
  3. /****** Object:  StoredProcedure [dbo].[USP_getCountryInfo]    Script Date: 12/18/2019 10:24:57 PM ******/    
  4. SET ANSI_NULLS ON    
  5. GO    
  6. SET QUOTED_IDENTIFIER ON    
  7. GO    
  8. ALTER Proc [dbo].[USP_getCountryInfo]    
  9. @ProductId int    
  10. As    
  11. Begin    
  12.     select pci.* from ProductCountryInformation pci     
  13.     left join Product p on pci.ProductId=p.ProductId     
  14.     where pci.ProductId=@ProductId    
  15. End  
With this step we have successfully completed our front end, web API, and back end coding. 
 

Conclusion

 
In this article, I have discussed how to create nested grid in Angular 8 Application. In my next article, which is a continuation of this part, we are going to learn about the JavaScript function tolocalestring() by changing the price by country, which will give their appropriate currency format.
 
Please give your valuable feedback/comments/questions about this article. Please let me know if you liked and understood this article and how I could improve it.