【问题标题】:How to dynamically bind angular material table with data from backend?如何将角度材料表与后端数据动态绑定?
【发布时间】:2020-03-08 22:12:12
【问题描述】:

我正在尝试基于此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

【问题讨论】:

    标签: javascript html angular angular-material


    【解决方案1】:

    试试这样:

    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);
            })
      }
    

    【讨论】:

    • 显示完整的结果输出
    • 我的意思是console.log(result)
    • 你已经显示{id: 1, technologyName: "Python", description: "Python123", commission: "20", imageURL: "https://cutt.ly/gePgUvn", …}
    • ... 没有帮助,您需要复制并粘贴完整的对象,以便我可以看到属性
    • 解决了。除了 adminUser 的每个单元格显示为 null 的缺失值之外,其余的一切都工作正常。我从 html 文件中删除了本机 html 表格标签 tr,td 并且工作正常。非常感谢:)
    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2019-05-13
    • 2020-12-17
    • 2019-11-30
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多