You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将JSON中的car数据关联至ng2-smart-table并展示指定字段?

How to Display Car Data in ng2-smart-table

First, ensure you’ve installed ng2-smart-table and imported its module in your Angular module—this is a common missed step!

// app.module.ts (or your feature module)
import { Ng2SmartTableModule } from 'ng2-smart-table';

@NgModule({
  imports: [
    // ... other imports like BrowserModule, HttpClientModule
    Ng2SmartTableModule
  ]
})
export class AppModule { }

Next, set up your component to fetch the data and configure the table:

Component Code (component.ts)

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-car-table',
  templateUrl: './car-table.component.html'
})
export class CarTableComponent {
  // Define table column settings
  tableSettings = {
    columns: {
      carId: {
        title: 'Car ID' // Customize the column display name
      },
      carName: {
        title: 'Car Name'
      },
      carBurant: {
        title: 'Fuel Type' // Renamed for better readability
      }
    },
    // Optional: Enable default features like filtering/sorting
    filter: true,
    sort: true
  };

  // Store the car data for the table
  carData: any[] = [];

  constructor(private http: HttpClient) {
    // Fetch your JSON data (replace with your actual API endpoint)
    this.http.get('your-api-endpoint-url').subscribe((response: any) => {
      // Extract the nested car array from the response
      this.carData = response.data.car;
    });
  }
}

Template Code (component.html)

Add the ng2-smart-table component to your template, binding the settings and data source:

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

Quick Explanation:

  • Data Extraction: The key part is accessing response.data.car—since your car array is nested inside the top-level data object, we assign this array directly to the table’s source (carData in our code).
  • Column Mapping: Each key in the columns object matches exactly the property names in your car objects (carId, carName, carBurant). You can tweak the title to make columns more user-friendly.
  • Extra Features: If you want to add editing, pagination, or other tools, just extend the tableSettings object with ng2-smart-table’s built-in options (check the library’s docs for details).

This should get your car data displaying perfectly in the table!

内容的提问来源于stack exchange,提问作者Zako

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:19:22