-2

I am using ng2-smart-table for the tabular representation of data received over rest response. But one of the elements is complex. The intention is to display categoryName under category column.

category: {id: 1, categoryName: "category 1", active: true, createdBy: null, createdOn: null, …}

My "column" in settings looks like...

columns: {
      id: {
        title: 'ID',
        type: 'number',
      },
      salesExecutive: {
        title: 'Sales Executive',
        type: 'string',
      },
      distributor: {
        title: 'Distributor',
        type: 'string',
      },
      product: {
        title: 'Product',
        type: 'string',
      },
      category: {
        title: 'Category',
        //***************** this must display "categoryName" from the complex "category" object
        type: 'string',
      },
      discount: {
        title: 'Discount',
        type: 'string',
      },
      flavor: {
        title: 'Flavor',
        type: 'string',
      },
      promotion: {
        title: 'Promotion',
        type: 'string',
      },
      scheme: {
        title: 'Scheme',
        type: 'string',
      },
    },

Have observed some suggestions to use renderComponent. But dint see better examples.

Renjith
  • 1,122
  • 1
  • 19
  • 45
  • 1
    The example for renderComponent is online accessible: https://github.com/akveo/ng2-smart-table/blob/master/projects/demo/src/app/pages/examples/custom-edit-view/advanced-example-custom-editor.component.ts – enno.void Jul 31 '20 at 12:46

1 Answers1

0

I resolved this issue with the help of an example in the comments section. https://github.com/akveo/ng2-smart-table/blob/master/projects/demo/src/app/pages/examples/custom-edit-view/advanced-example-custom-editor.component.ts

Posting my code in case if it helps somebody.

My json looks similar to the one below.

{
  {id: "1"},
  {salesExecutive: "Renjith"}
  .
  .
  .
  category: {
   id: "1",
   categoryName: "abcd", ........
  }

}

First of all primitive types cannot handle this. So, specify the type as custom in the settings. So we need to supply a custom component that can extract the categoryName from complex category tag. This component must be specified under the renderComponent

category: { title: 'Category', type: 'custom', renderComponent: CustomCategoryDataComponent, },

Now create a custom component.

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

import { ViewCell } from 'ng2-smart-table';


@Component({
    template: `
      {{renderValue}}
    `,
  })
export class CustomCategoryDataComponent implements ViewCell, OnInit {

    value: string | number;
    rowData: any;   //represents the entire row

    //this is there the result is stored and is rendered in the template
    renderValue: string;  

    ngOnInit(): void {
        this.renderValue = this.rowData.category.categoryName;
        console.log("Category: "+this.renderValue);
    }

}
Renjith
  • 1,122
  • 1
  • 19
  • 45