Super Retarded Dog
Super Retarded Dog

Reputation: 87

Angular Material Table does not paginate when using a service

I used this exact stackblitz, but just modified the constructor to use a service instead of the function that generates users

But the data is not being paginated. Can anybody explain what I'm doing wrong or why this approach does/will not work?

component.ts

import {Component, ViewChild} from '@angular/core';
import {MatPaginator, MatSort, MatTableDataSource} from '@angular/material';
import { AdminService } from '../admin.service';
import { Profile } from 'models.model';

@Component({
  selector: 'table-overview-example',
  styleUrls: ['table-overview-example.css'],
  templateUrl: 'table-overview-example.html',
})
export class ManageYouthComponent {
  displayedColumns = ['unl_num', 'unl_name', 'unl_email', 'unl_gender'];
  dataSource: MatTableDataSource<Profile>;

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

  constructor(private adminService:AdminService) {
    this.adminService._getAllYouth().subscribe(response => {
      this.dataSource = new MatTableDataSource(response.data);
    })
  }

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

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }
}

The HTML is exactly the same, just modified to use the columns specified in my .ts file

Upvotes: 0

Views: 46

Answers (1)

FedG
FedG

Reputation: 1301

You have to syncronize:

 ngOnInit() {
     this.adminService._getAllYouth().subscribe(response => {
          this.dataSource = new MatTableDataSource(response.data);
          this.dataSource.paginator = this.paginator;
          this.dataSource.sort = this.sort;
        })
     }

When the view is ready the response from server is not arrived yet, so the dataSource is not defined yet.

Upvotes: 2

Related Questions