Receiving some date from a Mongo database. Table displays correctly but when I try to sort, it doesn't work. I've checked several solutions online, but do not manage to get it working.

export class RecommendationtabelComponent implements OnInit, AfterViewInit{
  recommendations: Recommendation[] = [];
  private recommendationsSub: Subscription;
  displayedColumns: string[] = ['Class', 'LOE', 'Recommendation', 'Guideline'];
  public dataSource = new MatTableDataSource<Recommendation>();


  @ViewChild(MatSort) sort: MatSort;

  constructor(private http: HttpClient,
    public getRecommendationsService: GetRecommendationService,
    public recommendationInformationService: RecommendationInformationService) {}

  ngOnInit() {
    this.getRecommendationsService.getRecommendations();
    this.recommendationsSub = this.getRecommendationsService.getRecommendationUpdateListener()
    .subscribe((recommendations: Recommendation []) => {
      this.recommendations = recommendations;
      this.dataSource.data = this.recommendations;
    });
  }

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

And here is the template that I use to display the table and the results

<div class="recommendations-container">
  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8">

  .....

    <ng-container matColumnDef="Guideline">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Guideline</th>
        <td mat-cell *matCellDef="let element">
            {{element.guideline}}

        </td>
        <td mat-footer-cell *matFooterCellDef></td>
    </ng-container>

    <ng-container matColumnDef="Loading">
      <td mat-footer-cell *matFooterCellDef colspan="6">
        Loading Data....
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns;sticky:true"></tr>
    <tr mat-row *matRowDef="let row;columns:displayedColumns"></tr>
    <tr mat-footer-row *matFooterRowDef="['Loading']" [ngClass]="{'hide':dataSource!=null}"></tr>

  </table>
</div>

0 Answers