2

As first I post my code

service.ts

import { Component, NgModule, OnInit, ViewChild, Directive, EventEmitter, Output, ElementRef } from '@angular/core';
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map'


@Component({
 styles: [],
 template: ""
})
export class PageService {


constructor(private http: Http) {}


    getAllPage() {
            //noinspection TypeScriptUnresolvedFunction
            return this.http.get(window.location.origin + "/app/json/profile.json").map(res => res.json());
    }
}

tablecomponent.ts

import { Component, NgModule, OnInit, ViewChild, Directive, EventEmitter, Output, ElementRef } from '@angular/core';
import { Ng2SmartTableModule, LocalDataSource } from 'ng2-smart-table';
import {Http} from '@angular/http';
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal';
import { DomSanitizer, SafeResourceUrl, SafeUrl, BrowserModule } from '@angular/platform-browser';
import ButtonProductRenderComponent from './button-product-render.component';
import * as _ from 'underscore';
import { PageService } from '../order-request';

@Component({
 styles: [],
 templateUrl: '../../templates/table/profile-table.html',
})
export class ProfileTableComponent implements OnInit{
    rows;
    datas;
    profilojson;
    source: LocalDataSource; // add a property to the component
    settings = {
        mode: 'external',
        add: {
            addButtonContent: "<i class='icon-plus'></i>",
            createButtonContent: "Conferma",
            cancelButtonContent: "Annulla"
        },
        delete: {
            deleteButtonContent: "Cancella"
        },
        edit: {
            editButtonContent: "<i class='icon-copy2'></i>"
        },
        sort: {
            sortDirection: true
        },
        actions: false,
        noDataMessage: "Nessun risultato trovato",
        columns: {
            groupID: {
                title: 'Group Id',
                filter: false,
                class: "colonneTabella",
                width: "15%"
            },
            groupName: {
                title: 'Group Name',
                filter: false,
                class: "colonneTabella",
                width: "15%"
            },
            groupDescr: {
                title: 'Group Description',
                filter: false,
                class: "colonneTabella",
                width: "25%"
            },
            functionList: {
                title: 'Function List',
                filter: false,
                class: "colonneTabella",
                width: "20%"}
            ,
            button: {
                title: 'Buttons',
                filter: false,
                class: "colonneTabella",
                type: 'custom',
                renderComponent: ButtonProductRenderComponent,
            }
        }
    };


        /*{
            groupID: this.datas.groupID,
            groupName: "QD4",
            groupDescr: "Amministratore",
            functionList: "C312D5"

        }*/
pages: LocalDataSource;  

constructor(private pageService:PageService) {
        this.pages = new LocalDataSource();

        pageService.getAllPage().toPromise().then(data => {
            this.pages.load(data); 
            //console.log(this.pages.find("id")); 
            this.pages.reset();
        });
    }       



/*
        let profileInput; 
        this.http.get('app/json/profileInput.json')
        .subscribe(res =>{
            profileInput = res.json()
            //console.log(JSON.stringify(profileInput));
            this.profileConstructor(profileInput.rows);
            }
        );*/




    profileConstructor(profileRows){
       /*console.log(JSON.stringify(
                _.object(JSON.stringify([_.object([profileRows], ['riga'])], [1, 2, 3, 4, 5]))
            )
       );*/
        /*function group(array) {
            var map = new Map;

            array.forEach(function (o) {
                var group = map.get(o[0]) || { groupID: o[0], groupName: o[1], groupDescr: o[3], functionList: [] };
                if (!map.has(o[0])) {
                    map.set(o[0], group);
                }

               // var evens = _.filter(o, function(item){ return item[0] == o[0]});
               array.forEach(function( o=2 ) {
                    group.functionList = [{
                        'id': o[2], 'value': o[4]
                    }];
               })
                //console.log(evens)
            });
            return [...map.values()];
        }

        var rows = profileRows,
            result = group(rows);

        console.log(JSON.stringify(result));*/

      /* var arr = profileRows.reduce((a, b) => {
  let flag = false,
    obj = {};
  a.forEach(item => {
    if (item.groupID === b[0] && item.groupName === b[1] && item.groupDescr === b[3]) {
      item.functionList= {'id': b[2], 'value': b[4]}
      flag = true;
    }
  });
  if (!flag) {
    obj[b[2]] = b[4];
    a.push({
      "groupID": b[0],
      "groupName": b[1],
      "groupDescr": b[3],
      "functionList": [][b[2]]
    });
  }
  return a;
}, []);

console.log(JSON.stringify(arr));*/
    } ;



   ngOnInit() {

  }

    onCreate(event: any) {
        console.log("ciao");
    }
    onEdit(modal){
        console.log('AAAAAAAAAAA');
        modal.open();
    }

}

And table template

<div class="col-md-6 col-lg-6 pull-left"><div class="pull-left filter-search"><input #search class="search" type="text" [ngModel]="mymodel" placeholder="Cerca" (ngModelChange)="onSearch(search.value)" ></div></div>
     <div class="col-md-6 col-lg-6 pull-right"><div class="pull-right filter-external"> <i class="icon-circle-plus pull-left" [routerLink]="['/aggiungi-gruppo']"></i><i class="icon-circle-right pull-right"></i></div></div>
    <ng2-smart-table [settings]="settings" [source]="pages" (custom)="modal.open()"></ng2-smart-table>   

JSON:

[  
   {  
      "groupID":1,
      "groupName":"GESTORE_PRATICHE",
      "groupDescr":"GESTORE PRATICHE",
      "functionList":[
         {  
            "id":1,
            "value":"canViewFolderManagement"
         }
         ] 

   },
   {  
      "groupID":2,
      "groupName":"ADM",
      "groupDescr":"AMMINISTRATORE",
      "functionList":[
         {  
            "id":1,
            "value":"canViewFolderManagement"
         },
         {  
            "id":2,
            "value":"canViewAdministrationManagement"
         },
         {  
            "id":3,
            "value":"canViewConventions"
         },
         {  
            "id":4,
            "value":"canViewProfiles"
         },
         {  
            "id":5,
            "value":"canManageProfiles"
         }
      ]
   },
   {  
      "groupID":3,
      "groupName":"BOM",
      "groupDescr":"OPERATORE DI BACK OFFICE",
      "functionList":[  
         {  
            "id":1,
            "value":"canViewFolderManagement"
         },
         {  
            "id":2,
            "value":"canViewAdministrationManagement"
         }
      ]
   }
]

At the end I have the following result:

enter image description here

How can I see datas in functionList column? my code doesn't work correctly, it just keep first level json data. Thanks

Jamil89
  • 165
  • 3
  • 14
  • you could use value prepare function for each function to get nested data – Karan Garg Jul 17 '17 at 14:48
  • thanks...i tried with valuePrepareFunction: (value) => { return JSON.stringify(value)} and it seems works (partial...i just see the datas as an array, for the moment :) ) – Jamil89 Jul 17 '17 at 14:59
  • best approach would be to modify the data(create a new array of object of just the data you need) after getting json from the server rather than feeding it directly to the table.that way you dont have to use valuepreparefunction every time – Karan Garg Jul 17 '17 at 15:01
  • The problem is that datas has to return this way, I can't modify the structure atm :( – Jamil89 Jul 17 '17 at 15:15
  • you dont need to change the structure at server side..you can change it on the client side..because if you use value prepare then even sorting wont work the easy way.before doing this just modify your data this.pages.load(data); – Karan Garg Jul 17 '17 at 15:18

2 Answers2

2

I have fixed this error by using valuePrepareFunction: (cell,row).

you can use the code below at column settings

functionList: {
    title: 'Function List',
    type:'html',
    valuePrepareFunction: (cell,row) => {
        var valueModelList = JSON.parse(row.functionList);
        var htmlEntity ="";
        valueModelList.foreach(valueModel=>{
            htmlEntity += valueModel.id+ " : " + valueModel.value + '<br>';
        })
        return htmlEntity;
    }
}

I hope it works

Leonardo Alves Machado
  • 2,747
  • 10
  • 38
  • 53
0

You have 2 options: using custom render components, or mapping row value for the column. In case it is simple embedded values, 2nd is more preferable for me. See sample: categoryLabel and categoryName:

settings = {
    add: {
        addButtonContent: '<i class="nb-plus"></i>',
        createButtonContent: '<i class="nb-checkmark"></i>',
        cancelButtonContent: '<i class="nb-close"></i>',
    },
    edit: {
        editButtonContent: '<i class="nb-edit"></i>',
        saveButtonContent: '<i class="nb-checkmark"></i>',
        cancelButtonContent: '<i class="nb-close"></i>',
    },
    delete: {
        deleteButtonContent: '<i class="nb-trash"></i>',
        confirmDelete: true,
    },
    columns: {
        categoryLabel: {
            title: 'Category Label',
            valuePrepareFunction: (cell, row) => row.category.label,
        },
        categoryName: {
            title: 'Category Name',
            valuePrepareFunction: (cell, row) => row.category.name,
        },
        likes: {
            title: 'Likes Amount',
        },
Oleksandr Yefymov
  • 6,081
  • 2
  • 22
  • 32