0
votes

I use a Angular Material Table in my project. The data for the table will be past by a parent component via Input. This works fine. I also want to add a paginator to my table and one column should be sortable. But when setting the sort and paginator I get the error "....can not set .sort of undefined".

<div id="table-overflow">
    <mat-table [dataSource]="dataSourceLog" class="mat-elevation-z8" matSort matSortDisableClear>
        <ng-container matColumnDef="actionTS">
            <mat-header-cell *matHeaderCellDef mat-sort-header>TimeStamp</mat-header-cell>
            <mat-cell *matCellDef="let element"> {{element.actionTSFormated}} </mat-cell>
        </ng-container>
        /* some more columns*/
        <mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
</div>
<mat-paginator [pageSizeOptions]="[10, 20, 50]" showFirstLastButtons></mat-paginator>

.ts file

export class ProtocolLogTable implements OnInit{
    @Input() dataSourceLog: MatTableDataSource<DataLog>;
    timestampFrom: string;
    timestampTo: string;

    displayedColumns: string[] = ['actionTS' /* some more columns */];

    @ViewChild(MatPaginator) paginator: MatPaginator;
    @ViewChild(MatSort) sort: MatSort;

    ngOnInit() {
        this.dataSourceLog.sort = this.sort;
        this.dataSourceLog.paginator = this.paginator;
    }
}
1
if you can try use primeng for tables - it give much more poweryehonatan yehezkel

1 Answers

1
votes

Probably you don't get data immediately after creating the component. Try to move your code from ngOnInit to @Input setter like this

public dataSourceLogValue: MatTableDataSource<DataLog>;

@Input()
public set dataSourceLog(value: MatTableDataSource<DataLog>) {
  if (value) {
    this.dataSourceLogValue = value;
  }
}

And be sure that you renamed dataSourceLog to dataSourceLogValue in template.