如何动态绑定角度材料表与后端数据?

时间:2019-11-13 06:40:26

标签: javascript html angular angular-material

我试图基于此Angular Material Table Dynamic Columns without model将mat-table与来自后端api的数据绑定。这是.ts文件的内容


    technologyList = [];
      listTechnology = function () {
        this.http.get("https://localhost:44370/api/admin").subscribe(
          (result: any[]) => {
            this.technologyList = result;
            //creating table begins here
            var displayedColumns = Object.keys(this.technologyList[0]);
            var displayedRows = Object.entries(this.technologyList[0]);
            this.dataSource = new MatTableDataSource(this.technologyList);
            }

我从后端得到technologyList的响应,这是 >


    Array(2)
    0: {id: 1, technologyName: "Python", description: "Python123", commission: "20", imageURL: "https://cutt.ly/gePgUvn", …}
    1: {id: 2, technologyName: "Ruby", description: "Python123", commission: "30", imageURL: "https://cutt.ly/gePgUvn", …}
    length: 2

我正在尝试使用.html文件将其与html绑定 >


        <div>
        <mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">

            <ng-container *ngFor="let disCol of displayedColumns; let colIndex = index" matColumnDef="{{disCol}}">
                <mat-header-cell *matHeaderCellDef>{{disCol}}</mat-header-cell>
                <mat-cell *matCellDef="let element "> {{element[disCol]}}
                </mat-cell>
            </ng-container>

            <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
            <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
    </div>

输出为空白的白色块。我在这里做错了什么?任何帮助将不胜感激,谢谢。

建议的更改后的响应 output table

1 个答案:

答案 0 :(得分:0)

尝试这样:

Working Demo

  displayedColumns = [];
  dataSource;


 listTechnology = function () {
        this.http.get("https://localhost:44370/api/admin").subscribe(
          (result: any[]) => {
            this.technologyList = result;
            this.displayedColumns = Object.keys(this.technologyList[0]);
            this.dataSource = new MatTableDataSource(this.technologyList);
        })
  }