1

I created my own generic component with Material Table to use it in my application. So the problem is with sorting - it doesn't work at all. The arrow next to the column header shows but nothing happen. I found that it can be problem with ngIf over <table but.. I don't have it (only inside of the table but these are not the problem). Maybe someone can help me with that?

Component:

@ViewChild(MatSort, {static: true}) sort: MatSort;
@Input() data: any[] = [];
@Input() columns: GridColumn[] = [];
displayedColumns: string[] = [];
dataSource: MatTableDataSource<any>;

ngOnInit() {
for (const column of this.columns) {
  this.displayedColumns.push(column.id);
}

this.dataSource = new MatTableDataSource<any>(this.data);
}

ngAfterViewInit() {
this.dataSource.sort = this.sort;
}

getValue(object: any, path: string) {
return getNestedValue(object, path);
}

And the template:

<table class="w-100" mat-table [dataSource]="data" matSort>
 <ng-container *ngFor="let column of columns">

  <ng-container *ngIf="!column.content" cdkColumnDef="{{column.id}}">
   <th cdk-header-cell *cdkHeaderCellDef mat-sort-header>{{column.label | translate}}</th>
   <td cdk-cell class="position-relative" *cdkCellDef="let row">{{row[column.id]}}</td>
  </ng-container>

  <ng-container *ngIf="column.content" cdkColumnDef="{{column.id}}">
   <th cdk-header-cell *cdkHeaderCellDef>{{column.label | translate}}</th>
   <td cdk-cell class="position-relative" *cdkCellDef="let row">
    <ng-container [ngTemplateOutlet]="column.content"
                  [ngTemplateOutletContext]="{record: row, value: column.field ? getValue(row, column.field) : null}">
    </ng-container>
   </td>
  </ng-container>

 </ng-container>

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

EDIT: Stackblitz: https://stackblitz.com/edit/angular-b9cdqt

3
  • Can you please reproduce your issue in stackblitz? Commented Jul 28, 2020 at 12:39
  • @yurzui I just added stackblitz link to the question but it's not working correctly yet (I have some little problem with stackblitz configuration, probably in the module file), maybe you will display table faster than me Commented Jul 28, 2020 at 13:41
  • Done, problem is reproduced, stackblitz link in the question Commented Jul 28, 2020 at 14:00

1 Answer 1

1

The reason for this is that there is no reactive flow in your example.

You have no connection to MatTableDataSource since you passed plain array to dataSource input property instead.

A quick fix should be:

[dataSource]="dataSource" 

Forked Stackblitz

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.