How to Create a Nested Grid Using Angular 8
Join the DZone community and get the full member experience.
Join For FreeIn this article, we will learn how we create a nested grid in Angular 8. 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.
Prerequisites
- Basic knowledge of Angular.
- Visual Studio Code must be installed.
- Angular CLI must be installed.
- Node.js must be installed.
Building the Frontend
Step 1
Let's create an Angular project using the following npm command.
xxxxxxxxxx
ng new nestedGrid
Step 2
Open the newly created project in Visual Studio code and install Bootstrap in the project.
xxxxxxxxxx
npm install bootstrap --save
Now, open styles.css file and add the Bootstrap file reference. To add a reference in styles.css file, add this line:
xxxxxxxxxx
@import '~bootstrap/dist/css/bootstrap.min.css';
You may also like: Angular 7 + Spring Boot Application: Hello World Example.
Step 3
Now, let's create a new component by using the following command.
xxxxxxxxxx
ng g c product
Step 4
Now, create a new service using the following command.
xxxxxxxxxx
ng generate service product
Step 5
Now, open the product.component.html and paste the following code to see the HTML template.
xxxxxxxxxx
<div class="card">
<div class="card-body pb-0">
<h4 style="text-align: center;">Example of Angular Nested Grid</h4>
<div class="row">
<div class="col-12 col-md-12">
<div class="card">
<div class="card-body position-relative">
<div class="table-responsive cnstr-record product-tbl">
<table class="table table-bordered heading-hvr">
<thead>
<tr>
<th> </th>
<th width="50">Art.No
</th>
<th>Brand</th>
<th>
Price/Unit</th>
<th>Provider</th>
<th>P. Art. N</th>
<th>S. A/C</th>
<th>Buy A/C</th>
</tr>
</thead>
<tbody *ngFor="let product of products; let i = index">
<tr>
<td align="center">
<a class="expand-row" *ngIf="!hideme[i]" (click)="showProductCountryInfo(i,product.ProductId)">
<img src="../../assets/Images/plus.png" />
</a>
<a class="expand-row" *ngIf="hideme[i]" (click)="hideme[i] = !hideme[i]">
<img src="../../assets/Images/minus.png" />
</a>
</td>
<td align="center">{{product.ArtNo}}</td>
<td>{{product.Brand}}</td>
<td>{{product.Price }}</td>
<td>{{product.Provider}}</td>
<td>{{product.ProviderArtNo}}</td>
<td>{{product.SalesAccount}}</td>
<td>{{product.BuyAccount}}</td>
</tr>
<!-- <div id="myresult" class="img-zoom-result"></div> -->
<tr [hidden]="!hideme[i]" class="sub-table no-bg">
<td align="center"> </td>
<td colspan="15" class="p-0">
<table class="table mb-0 table-striped">
<thead class="bg-dark text-white">
<tr>
<th>CountryName</th>
<th>Price/Unit</th>
<th>Sales Account</th>
<th>Buy Account</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let productCountryInfo of productCountryInformation[i]">
<td>{{productCountryInfo.CountryName}}</td>
<td>{{productCountryInfo.Price}}</td>
<td>{{productCountryInfo.SalesAccount}}</td>
<td>{{productCountryInfo.BuyAccount}}</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
Step 6
After then open product.component.ts file and add the following code in this file where our logic has been written.
xxxxxxxxxx
import { Component, OnInit } from '@angular/core';
import { ProductsService } from './products.service';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
products = [];
countryCode: any;
currencySymbol:any;
productCountryInformation: any = [];
hideme = [];
Index: any;
countryId: any;
country: any;
priceToDisplay=[];
constructor(private _productService: ProductsService) {
}
ngOnInit() {
this.countryId=0;
this.getProducts(this.countryId);
}
public getProducts(countryId) {
let data = [];
this._productService.getAllProducts(countryId).subscribe((data: any) => {
this.products =data;
})
}
public showProductCountryInfo(index,productId) {
this._productService.countryInfo(productId).subscribe((res:any)=>{
this.productCountryInformation[index] = res;
})
this.hideme[index] = !this.hideme[index];
this.Index = index;
}
}
Step 7
Next open product.component.css file and paste the code for styling.
xxxxxxxxxx
@charset "utf-8";
/* CSS Document */
@media all{
*{padding:0px;margin:0px;}
div{vertical-align:top;}
img{max-width:100%;}
html {font-smoothing:antialiased; osx-font-smoothing:grayscale;}
body{overflow:auto!important; width:100%!important;}
html, body{background-color:#e4e5e6;}
html {position:relative; min-height:100%;}
.card{border-radius:4px;}
.card-header:first-child {border-radius:4px 4px 0px 0px;}
/*Typekit*/
html, body{font-family:'Roboto', sans-serif; font-weight:400; font-size:13px;}
body{padding-top:52px;}
p{font-family:'Roboto', sans-serif; color:#303030; font-weight:400; margin-bottom:1rem;}
input, textarea, select{font-family:'Roboto', sans-serif;}
h1,h2,h3,h4,h5,h6{font-family:'Roboto', sans-serif; font-weight:700;}
h1{font-size:20px; color:#000000; margin-bottom:10px;}
h2{font-size:30px;}
h3{font-size:24px;}
h4{font-size:18px;}
h5{font-size:14px;}
h6{font-size:12px;}
.row {margin-right:-8px; margin-left:-8px;}
.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:8px; padding-left:8px;}
.card-header{background-color:#f0f3f5; border-bottom:1px solid #c8ced3; font-size:13px; font-weight:600; color:#464646; text-transform:uppercase; padding:.75rem 8px;}
.cnstr-record th{white-space:nowrap;padding:.45rem .2rem; font-size:13px; border-bottom-width:0px!important;}
.cnstr-record thead{background:#f0f3f5;}
.cnstr-record .form-control{font-size:13px; padding:0px 0rem 0px 0.2rem; height:calc(2rem + 2px);}
.cnstr-record select.form-control{padding-left:.05rem;}
.cnstr-record .table td, .cnstr-record .table th {vertical-align:middle;}
.cnstr-record .table td{padding:.3rem;}
.cnstr-record .table td h4{margin:0px;}
.wp-50{width:50px;}
.wp-60{width:60px;}
.wp-70{width:70px;}
.wp-80{width:80px;}
.wp-90{width:90px;}
.wp-100{width:100px;}
.mw-auto{min-width:inherit;}
.expand-row{width:100%; border:solid 1px #596269; display:inline-block; border-radius:3px; width:16px; height:16px; vertical-align:top; background:#596269; color:#ffffff!important;}
.expand-row img{vertical-align:top; position:relative; top:2px;}
.sub-table th{font-weight:400; font-size:12px;}
.sub-table td{background:#efefef;}
.no-bg td{background:inherit;}
.mw-100{max-width:100%;}
}
Step 8
At last, open product.service.ts file and add services to call our API.
xxxxxxxxxx
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class ProductsService {
private url = "";
constructor(public http: HttpClient) {
}
getAllProducts(countryCode) {
this.url = 'http://localhost:49661/api/Company/getAllProducts?countryCode='+countryCode;
return this.http.get<any[]>(this.url);
}
countryInfo(productId) {
this.url = 'http://localhost:49661/api/Company/getProductCountryInformation?productId='+productId;
return this.http.get<any[]>(this.url);
}
}
Step 9
Its time to see the output in your terminal type ng serve -o
to compile and open it in the browser. After loading our page, you can see the output like in the below images.
Here, I am taking a product, for example. The 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 the parent grid so that you can see the resulting nested grid based on the index, (i.e if you click on the very first plus icon, you can only see its first product-related information. If you click on the second plus icon, then their product-related information would show.)
Now, the frontend is done and it's time to add server-side 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.
Step 2
Choose the Create option and select ASP.NET web application.
Step 3
Select Web API and click Ok.
Step 4
Now right click on controller and then add a new item.
Step 5
Choose Ado.net Entity Data Model and then click on Add.
Step 6
The next step is the EF Designer, just click on next.
Step 7
A new pop-up will appear. Click on next. If yours isn't established, then click on a new connection
Step 8
Copy your database connection server name and paste it in the server name textbox. You will see all the databases available — select your database and click ok.
Step 9
The next popup will show. Paste your database server name, choose the correct database, test the connection, and click next. Here, in the new screen, select your tables and store the procedure. Then, click finish.
Our next step is to right-click on the controllers folder and add a new controller. Name it "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
xxxxxxxxxx
using System.Linq;
using System.Web.Http;
using CompanyDetails.Models;
namespace CompanyDetails.Controllers
{
[RoutePrefix("api/Company")]
public class CompanyController : ApiController
{
CompanyEntities2 DB = new CompanyEntities2();
[HttpGet]
[Route("getAllCountry")]
public object getAllCountry()
{
return DB.Countries.ToList();
}
[HttpGet]
[Route("getAllProducts")]
public object getAllProducts(string countrycode)
{
var productDetails = DB.USP_GetAllProducts().ToList();
return productDetails;
}
[HttpGet]
[Route("getProductCountryInformation")]
public object getProductCountryInformation(int ProductId)
{
var prod = DB.USP_getCountryInfo(ProductId).ToList();
return prod;
}
}
}
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 on a different port than your server, then, to avoid a Cross-Origin-Resource-Sharing issue, you have to add the following code in the webapiconfig.cs file:
xxxxxxxxxx
EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
Building the Backend
Here, we will continue to build out our backend with SQL server. The very first step is to create a database.
Create a 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.
xxxxxxxxxx
create database product
Step 2
Create a product table using the following code:
xxxxxxxxxx
USE [Product]
GO
/****** Object: Table [dbo].[Product] Script Date: 12/18/2019 10:23:19 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Product](
[ProductId] [int] IDENTITY(1,1) NOT NULL,
[ProductCountryInformationId] [int] NULL,
[ArtNo] [nvarchar](50) NULL,
[Provider] [nvarchar](50) NULL,
[ProviderArtNo] [nvarchar](50) NULL,
[Brand] [nvarchar](50) NULL,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ProductId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Product] WITH CHECK ADD CONSTRAINT [FK_Product_ProductCountryInformation] FOREIGN KEY([ProductCountryInformationId])
REFERENCES [dbo].[ProductCountryInformation] ([ProductCountryInformationId])
GO
ALTER TABLE [dbo].[Product] CHECK CONSTRAINT [FK_Product_ProductCountryInformation]
GO
Make product ID the primary key.
Step 3
Create a product information table using the following code:
-
SQL
xxxxxxxxxx
137
1USE [Product]
2GO
34/****** Object: Table [dbo].[ProductCountryInformation] Script Date: 12/18/2019 10:24:02 PM ******/
5SET ANSI_NULLS ON
6GO
78SET QUOTED_IDENTIFIER ON
9GO
1011CREATE TABLE [dbo].[ProductCountryInformation](
12[ProductCountryInformationId] [int] NOT NULL,
13[Price] [decimal](18, 2) NULL,
14[BuyAccount] [nvarchar](50) NULL,
15[SalesAccount] [nvarchar](50) NULL,
16[CountryName] [nvarchar](50) NULL,
17[ProductId] [int] NULL,
18CONSTRAINT [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 = ON) ON [PRIMARY]
22) ON [PRIMARY]
23GO
2425ALTER TABLE [dbo].[ProductCountryInformation] WITH CHECK ADD CONSTRAINT [FK_ProductCountryInformation_Product] FOREIGN KEY([ProductId])
26REFERENCES [dbo].[Product] ([ProductId])
27GO
2829ALTER TABLE [dbo].[ProductCountryInformation] CHECK CONSTRAINT [FK_ProductCountryInformation_Product]
30GO
3132ALTER TABLE [dbo].[ProductCountryInformation] WITH CHECK ADD CONSTRAINT [FK_ProductCountryInformation_ProductCountryInformation] FOREIGN KEY([ProductCountryInformationId])
33REFERENCES [dbo].[ProductCountryInformation] ([ProductCountryInformationId])
34GO
3536ALTER TABLE [dbo].[ProductCountryInformation] CHECK CONSTRAINT [FK_ProductCountryInformation_ProductCountryInformation]
37GO
Now, it's time to add some store procedures.
Step 4
All you have to do is paste the following code in a new query:
xxxxxxxxxx
USE [Product]
GO
/****** Object: StoredProcedure [dbo].[USP_GetAllProducts] Script Date: 12/18/2019 10:24:35 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [dbo].[USP_GetAllProducts]
As
Begin
Select p.*,pci.Price,pci.BuyAccount,pci.SalesAccount from [Product] p
left join [ProductCountryInformation] pci
on p.ProductCountryInformationId=pci.ProductCountryInformationId
End
USE [Product]
GO
/****** Object: StoredProcedure [dbo].[USP_getCountryInfo] Script Date: 12/18/2019 10:24:57 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [dbo].[USP_getCountryInfo]
@ProductId int
As
Begin
select pci.* from ProductCountryInformation pci
left join Product p on pci.ProductId=p.ProductId
where pci.ProductId=@ProductId
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 a 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.
Further Reading
Opinions expressed by DZone contributors are their own.
Comments