2

I have been looking for a solution to this issue but unfortunately couldn't make it work. I followed the official angular material guide and wrote the following code, which is supposed to support pagination and sorting of the material table:

export class RecentAnnouncementsComponent implements OnInit, AfterViewInit {

  displayedColumns: string[] = ['created_utc', 'name', 'title'];
  dataSource = new MatTableDataSource<any>();
  items: ItemData[] = [];

  constructor(private firebaseService: FirebaseService) { }

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

  ngOnInit(): void {
    
  }

  ngAfterViewInit() {
    this.firebaseService.getItems().subscribe(result => {
      this.items = result;
      this.dataSource.data = this.items;
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    });
  }
}

The following error persists:

Property 'paginator' has no initializer and is not definitely assigned in the constructor.

I tried to modify the code according to these answers but nothing worked. At most, I got rid of errors but the pagination and sorting buttons didn't affect the table items.

I would be very thankful for a suggestion to solve this issue.

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286

2 Answers2

5

I assume you're working on the latest version of Angular. I do, and I got this working with:

  @ViewChild(MatSort) sort: MatSort = new MatSort();
  @ViewChild(MatPaginator) paginator: MatPaginator = new MatPaginator(new MatPaginatorIntl(), ChangeDetectorRef.prototype);
Christine
  • 106
  • 1
  • 5
0

I do this to solve:

@ViewChild(MatSort) sort: MatSort = <MatSort>{};
@ViewChild(MatPaginator) paginator: MatPaginator = <MatPaginator>{};

This way also works:

@ViewChild(MatSort) sort: MatSort | null = null;
@ViewChild(MatPaginator) paginator: MatPaginator | null = null;
ailtonbsj
  • 191
  • 1
  • 10