Skip to main content

How to Create Nested Grid in Angular 8

How to Create Nested Grid in Angular 8

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

ng new nestedGrid   

Step 2

Open the newly created project in Visual Studio code and install bootstrap in this project 

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:

@import '~bootstrap/dist/css/bootstrap.min.css'; 

Step 3

Now, let's create a new component by using the following command.

ng g c product  

Step 4

Now create a new service using the following command.

ng generate service product  

Step 5

Now, open the 'product.component.html' and paste the following code to see the HTML template. 

<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.

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.

@charset "utf-8";   
/* CSS Document */  
@media all{  
    *{padding:0px;margin:0px;}  
div{vertical-align:top;}  
img{max-width:100%;}  
html {-webkit-font-smoothing:antialiased; -moz-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.

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 browser.

After loading our page you can see the output like in the below images:

This is image title

This is image title

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.)

Comments

Popular posts from this blog

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...