Mat-table jump to page of searched item

13 Views Asked by At

I have a mat-table with columns "name" and "population". It is a table that lists cities. In the table I use pagination. I want to search for a city name and jump to the page that has that city. I do not want to filter the table and show only this city. I want to keep the whole data in the table and jump to the specific page.

Example: I search for the city "Berlin". The pagination shows 5 items at once. "Berlin" is on page 3. Now I want the table to display page 3.

Has anyone an idea how to do that?

1

There are 1 best solutions below

0
Benjamin On

I found the answer by myself

Here is the code

interface City {
  name: string;
  population: number;
};
    
cities: City[] = ...
onlyCity = 'Berlin'
@ViewChild(MatPaginator) paginator: MatPaginator;
    
this.dataSource = new MatTableDataSource<City>(cities);
const onlyCityIndex = this.dataSource.data.map((city) => {
  return city.name;
}).indexOf(onlyCity);
const pageNumber = Math.floor(onlyCityIndex / this.paginator.pageSize);
this.paginator.pageIndex = pageNumber;