How can I create dynamic columns in an Angular Kendo Grid with Typescript in a Pivot table format?

Is there a way to generate dynamic columns in Angular 4 and higher with Kendo Grid using TypeScript, similar to a pivot style?

I attempted to use the Kendo Auto-Generated column examples available on the Telerik/Progress website.

You can find the sample examples provided by Kendo at this link:

https://www.telerik.com/kendo-angular-ui/components/grid/columns/auto-generated/

I am looking for a Pivot Style Kendo Grid

Answer №1

Here is a modified code snippet that showcases how to customize the Kendo Grid in Angular. This example was inspired by a previously generated grid with auto columns and has been tailored for specific needs - code by: Udhaya Kannan

app.component.ts
-----------------

import { Component } from "@angular/core";
import { sampleProducts } from "./products";
import { Product } from "./product.model";
import { distinct } from "@progress/kendo-data-query";

interface ColumnSetting {
  field: string;
  title: string;
  format?: string;
  type: "text" | "numeric" | "boolean" | "date";
}

interface GroupColumnSetting {
  title: string;
  supplierId: number;
}

@Component({
  selector: "my-app",
  template: `
    <kendo-grid
      [kendoGridBinding]="gridData"
      [filterable]="true"
      scrollable="none"
    >
      <kendo-grid-column
        field="ProgramCode"
        title="Main Program Code"
      ></kendo-grid-column>
      <kendo-grid-column-group
        [headerStyle]="{ 'text-align': 'center' }"
        *ngFor="let groupColumn of groupColumns"
        title="{{ groupColumn.title }}"
        [locked]="false"
      >
        <kendo-grid-column field="ProductID" title="Product-ID">
          <ng-template kendoGridCellTemplate let-dataItem>
            {{ getProductID(dataItem.ProductID, groupColumn.supplierId) }}
          </ng-template>
        </kendo-grid-column>
        <kendo-grid-column field="SupplierID" title="Supplier-ID">
          <ng-template kendoGridCellTemplate let-dataItem>
            {{ getSupplierID(dataItem.ProductID, groupColumn.supplierId) }}
          </ng-template>
        </kendo-grid-column>
        <kendo-grid-column field="ProductName" title="Product-Name">
          <ng-template kendoGridCellTemplate let-dataItem>
            {{ getProductName(dataItem.ProductID, groupColumn.supplierId) }}
          </ng-template>
        </kendo-grid-column>
      </kendo-grid-column-group>
    </kendo-grid>
  `
})
export class AppComponent {
  public gridData: any[] = distinct(sampleProducts, "ProgramCode");
  public arrayResult: Product[] = sampleProducts;

  public isAssociatedIds(
    supplierID: number,
    groupColumnSupplierID: number
  ): boolean {
    return supplierID == groupColumnSupplierID;
  }

  public getProductName(productID: number, supplierID: number): string {
    const localProduct = this.arrayResult.find(
      x => x.ProductID == productID && x.SupplierID == supplierID
    );

    return localProduct.ProductName;
  }

  public getProductID(productID: number, supplierID: number): number {
    const localProduct = this.arrayResult.find(
      x => x.ProductID == productID && x.SupplierID == supplierID
    );

    return localProduct.ProductID;
  }

  public getSupplierID(productID: number, supplierID: number): number {
    const localProduct = this.arrayResult.find(
      x => x.ProductID == productID && x.SupplierID == supplierID
    );

    return localProduct.SupplierID;
  }

  public groupColumns: GroupColumnSetting[] = [
    {
      title: "Supplier Test 1",
      supplierId: 1
    },
    {
      title: "Supplier Test 2",
      supplierId: 2
    }
  ];

  public columns: ColumnSetting[] = [
    {
      field: "ProductName",
      title: "Product Name",
      type: "text"
    },
    {
      field: "UnitPrice",
      format: "{0:c}",
      title: "Unit Price",
      type: "numeric"
    },
    {
      field: "FirstOrderedOn",
      format: "{0:d}",
      title: "First Ordered",
      type: "date"
    }
  ];
}

product.model.ts
----------------
export class Product 
 {
    ProductID: number;
    ProductName: string;
    SupplierID: number;
    ProgramCode: string;
    CategoryID: number;
    QuantityPerUnit: string;
    UnitPrice: number;
    UnitsInStock: number;
    UnitsOnOrder: number;
    ReorderLevel: number;
    Discontinued: boolean;
    Category: Category;
    FirstOrderedOn: Date;
  }

  export class Category {
    CategoryID: number;
    CategoryName: string;
    Description: string;
  }
products.ts
-----------

export const sampleProducts = [
  {
    ProductID: 1,
    ProductName: "Chai",
    SupplierID: 1,
    ProgramCode: "ABC",
    CategoryID: 1,
    QuantityPerUnit: "10 boxes x 20 bags",
    UnitPrice: 18,
    UnitsInStock: 39,
    UnitsOnOrder: 0,
    ReorderLevel: 10,
    Discontinued: false,
    Category: {
      CategoryID: 1,
      CategoryName: "Beverages",
      Description: "Soft drinks, coffees, teas, beers, and ales"
    },
    FirstOrderedOn: new Date(1996, 8, 20)
  },
// Additional product entries here...
]
app.module.ts
-------------
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { GridModule } from '@progress/kendo-angular-grid';

import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule, BrowserAnimationsModule, FormsModule, GridModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})

export class AppModule { }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using webpack to bundle node_modules into your application

I am facing an issue while trying to load some modules like: moment echarts In my package.json file, I have the following versions specified: "echarts": "^3.1.10" "moment": "^2.14.1" However, I am encountering the errors below: VM2282:1 Uncaught Ref ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

Leveraging GetServerSideProps for Dynamic URL Query Parameters

While working on querying the parameter in the URL within getServerSideProps, I encountered an error where ID was undefined in the DetailThemepage function. My Next.js version is V.13 and the directory structure is app/detail/[id]/page.tsx. http://loca ...

Error: CORS not allowing origin access with Angular, Spring WebFlux, and Spring OAuth2 client

I am currently working on developing a straightforward web application using Angular. The goal is to be able to retrieve data from a battlenet resource server that is secured with oauth. My planned project structure includes: Angular Spring Boot as an oa ...

The request to search for "aq" on localhost at port 8100 using Ionic 2 resulted in a 404 error, indicating that the

Trying to create a basic app that utilizes an http request, but facing challenges with cors in ionic 2. To begin with, modifications were made to the ionic.config.json { "name": "weatherapp", "app_id": "", "v2": true, "typescript": true, "prox ...

Guide to seamlessly incorporate a HTML template into your Angular 7 project

I'm currently in the process of integrating an HTML template into my Angular 7 project, and unfortunately, it does not seem to be functioning as expected. To start off, I have placed the template files under assets/template/.. and included the necess ...

Is it possible for the ionic ionViewDidEnter to differentiate between pop and setRoot operations?

I am facing an issue with my ionic 3 page where I need to refresh the data on the page only if it is entered via a navCtrl.setRoot() and not when returned to from a navCtrl.pop(). I have been using ionViewDidEnter() to identify when the page is entered, bu ...

AG-Grid hierarchical data structure

Transitioning from kendo tree list to ag grid tree data grid, I am facing a challenge. My table data is currently formatted as shown below, but ag grid requires data in the form of a string array of nodes in a tree. How can I adapt or customize my existing ...

How to access type properties in typescript without using the "this" keyword

Below is a snippet of code that I am working with: class Player implements OthelloPlayer { depth; constructor(depth: number) { this.depth = depth; } getMove(state: OthelloState) { return this.MinimaxDecision(stat ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Convert TypeScript-specific statements into standard JavaScript code

For my nextjs frontend, I want to integrate authentication using a keycloak server. I came across this helpful example on how to implement it. The only issue is that the example is in typescript and I need to adapt it for my javascript application. Being u ...

Encountering a Runtime Exception while setting up a Client Component in the latest version of Next JS (v13.3

I am facing an issue with a component in my Next JS website. When I attempt to convert it into a Client Component, the page fails to load in the browser and I encounter the following unhandled runtime exception: SyntaxError: "undefined" is not va ...

The Angular 2 function within the subscribe method is being triggered before the request has finished processing

I have been attempting to extract a parameter from a URL and then passing it to another method. Below is the code snippet: ngOnInit() { this.getParamValues(); } getParamValues() { this.route.queryParams.subscribe(params => { ...

Is $onInit utilizing a separate scope for its execution?

HTML: <map street="{{firstunit.street}}"/> Component: @Component('CustomerService', { templateUrl: '/CustomerService/_UnitCard/MapComponent/Map.html', selector: 'map', bindings: { street: '@&a ...

Issue encountered while rendering the PrimeNG Galleria module

After upgrading my angular app to version 16 and PrimeNg components, I encountered an issue with version 16.0.0-rc.2. The component is not functioning properly and showing an error message: https://i.sstatic.net/nBRVl.png The error occurs in this portion ...

Comparison of Angular 2 Load Times on Desktop and Mobile Devices

I'm currently working on a webpage using Angular CLI and bootstrap version 4. I'm facing an issue specifically with the load times when accessed on mobile devices. Interestingly, the page loads in less than a second on desktop but takes over 10 s ...

After calling sequelize.addModels, a Typescript simple application abruptly halts without providing any error messages

My experience with Typescript is relatively new, and I am completely unfamiliar with Sequelize. Currently, I have only made changes to the postgres config in the .config/config file to add the dev db configuration: export const config = { "dev" ...

Enhance your TypeScript skills by leveraging types on the call() method in redux-saga

Is there a way to specify the types of a function using call()? Consider this function: export function apiFetch<T>(url: string): Promise<T> { return fetch(url).then(response => { if (!response.ok) throw new Error(r ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...