menu

Questions & Answers

Issue with setting DataSourcePaginator as Paginator in Angular

I'm following an example for creating a table with materials. However I am getting an issue creating a paginator. In the AfterViewInit I get the errors on the line this.dataSource.paginator = this.paginator; and I'm not sure how to resolve them

Type 'MatPaginator' is not assignable to type 'MatTableDataSourcePaginator'.
  Types of property 'page' are incompatible.
    Type 'EventEmitter<PageEvent>' is not assignable to type 'Subject<MatTableDataSourcePageEvent>'.
      Types have separate declarations of a private property 'currentObservers'. 

This is what my component looks like.

import { AfterViewInit, Component, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';

export interface Data {
  name: string;
  number: number;
}

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements AfterViewInit {
  displayedColumns: string[] = ['name', 'number'];
  dataSource: MatTableDataSource<Data>;

  @ViewChild(MatPaginator, {static:false}) paginator !: MatPaginator;
  @ViewChild(MatSort) sort = new MatSort();


  constructor() {
    const rows: Array<Data> =[];
    this.dataSource = new MatTableDataSource(rows);
  }

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

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();

    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
  }
}
Answers(1) :

Delete all your node modules and run ng add @angular/material. Easy Fix