1

I am trying to bind mat-table with data from backend api based on this Angular Material Table Dynamic Columns without model. Here is the .ts file content


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

I am getting response from backend as technologyListwhich is >


    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

I am trying to bind this with html using .html file as >


        <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>

The output is a blank white block. What am I doing wrong here? Any help would be much appreciated, thank you.

Response after the proposed change output table

stan_el
  • 83
  • 2
  • 5

1 Answers1

1

Try like this:

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);
        })
  }
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79