How can I add row numbers on a table with ajax data source

How can I add row numbers on a table with ajax data source

julian_dimitroffjulian_dimitroff Posts: 2Questions: 1Answers: 0

Hi there
I use Angular App and DataTables. In one of my components I have a DataTable which pulls data from an external API using the "ajax" property of the options object.

export class ChartsDetailsComponent implements OnInit {
   ngOnInit(): void {
       var opts: any = {
           ajax :{
              url: this.appConfigService.analyseConfig.chartsApiUrl + "/api/Charts/GetChartDetails?type=" + this.chartType,
              dataSrc: "ChartData." + this.chartType 
           }
       }
   }
}

The returned data in the data source contains only the columns that has to be displayed, but I would like to have a row number before the columns that are filled with the returned from the API data.
Is there a way to achieve this behavior?

Thanks in advance
Julian

Answers

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    One option os to loop through the data using ajax.dataSrc as a function. There are examples in the docs of using it as a function.

    Another option is this example that shows how to make an index column. It updates the index on each order or search operation. If you want to keep it statically assigned you can use the init event instead.

    Kevin

  • julian_dimitroffjulian_dimitroff Posts: 2Questions: 1Answers: 0

    Hi there @kthorngren ,
    Thanks for the quick answer. I've tried the first option, but the the returned data structure is dynamic. For example I have something like this:

    {
    "ChartData":{ 
    "MyChartType": [
     [{"data","data"}],
     [{"data","data"}],
     ]
    }
    }
    

    And this "MyChartType" is not always the same. If I do this:

    ajax :{
            url: this.appConfigService.analyseConfig.chartsApiUrl + "/api/Charts/GetChartDetails?type=" + this.chartType,
            dataSrc: function (json){
              //here I'll need the this.chartType variable in order to extract the data 
             // but the context of the function is not binded to the 
             // Angular component class and I do not have access to this variable
              return json;
            }
          },
    

    The problem is written as a comment in the code above. In other words I'll be able to alter the received json if I have access to the Angular class variable.

    The second option I think expects predefined empty 1st column in order to write there the row index, but I do not have access to the data, because it is from the API call.

    So I'm left with the first option, but I do not know is there a way to access that Angular class variable, if yes - then my problem is solved?

    Thanks in advance,
    Julian

This discussion has been closed.