angularng2-smart-table

ng2-smart-table: data from json


I would like to link my json data to ng2-smart-table

My json return a lot of datas

"data":{
   "name":"Myname",
   "email":"myemail@gmail.com",
   "car":[
      {
       "carId":"99",
       "carName":"mycar",
       "carBurant":"diesel"
      },
      {
       "carId":"88",
       "carName":"mycar2",
       "carBurant":"diesel"
      },
      {
       "carId":"77",
       "carName":"mycar3",
       "carBurant":"diesel",
      },
   ]
 }

I would like to put "carId" , "carName" and "carBurant" on my ng2-smart-table Could you help me please?


Solution

  • It's actually quite straight-forward if you happen to get a chance to have a look at the documentation here.

    Here, give this a try:

    import { Component } from "@angular/core";
    import { HttpClient } from "@angular/common/http";
    
    @Component({
      selector: "my-app",
      templateUrl: "./app.component.html",
      styleUrls: ["./app.component.css"]
    })
    export class AppComponent {
      settings = {
        columns: {
          carId: {
            title: "Car ID"
          },
          carName: {
            title: "Car Name"
          },
          carBurant: {
            title: "Car Burant"
          }
        }
      };
      data;
    
      constructor(private http: HttpClient) {}
    
      ngOnInit() {
        this.http.get("assets/user.json").subscribe(user => (this.data = user.car));
      }
    }
    

    And in your template:

    <ng2-smart-table 
      [settings]="settings"
      [source]="data">
    </ng2-smart-table>
    

    Here's a Working Sample StackBlitz for your ref.