Using a static array as datasource for mat-table

Viewed 18601

I'm trying to make use of the Angular Material table. I'm trying to use the same code as the examples they have but I tin into a problem when I have to define the [dataSource]="data".

This question may sound stupid but my table data is a simple array of objects, how can I implement that?

for the sake of explaining let's say my data looks like this:

public data = [{ ID: 1, Code: "Hi" }, { ID: 2, Code: "Bye" }];

Here's the code I currently have:

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="data">
        <ng-container matColumnDef="number">
            <mat-header-cell *matHeaderCellDef> Number </mat-header-cell>
            <mat-cell *matCellDef="let row"> {{ row.ID }} </mat-cell>
        </ng-container>

        <ng-container matColumnDef="Code">
            <mat-header-cell *matHeaderCellDef> Code </mat-header-cell>
            <mat-cell *matCellDef="let row">{{row.Code}}</mat-cell>
        </ng-container>

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

even if you use static datas you will have to instantiate a new DataSource.

mat-table always need a real DataSource in @Input. DataSource is an abstract class, so you have to implement a class who inherit from DataSource.

This DataSource must have a method "connect" implemented which will return an Observable of the data you want to display.

So in your case something like that should work ;

// in your component

interface MyDataType {
    ID: number;
    Code: string;
}

export class StaticDataSource extends DataSource<MyDataType> {
  constructor(private staticData: MyDataType[]) {
    super();
  }

  connect(): Observable<MyDataType[]> {
    return Observable.of(this.staticData);
  }

  disconnect() {}
}
...
this.staticDataSource = new StaticDataSource(data);

// in your template
 <mat-table #table [dataSource]="staticDataSource">
Related