Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Table: Detect what rows (items) are currently being displayed

I need some way to track what items (rows) in a Material Table are currently being displayed. According to the documentation, <mat-table> is built on top of <cdk-table>, giving it a viewChange property. My understanding is that this BehaviorSubject fires anytime the set of rows being displayed changes. For instance, there might be 400 total rows, but due to pagination, only 20 are on the screen. When the user clicks to go to the next page, this should cause viewChange to emit. Does anyone know how to use this property? I tried the following code, but it only fires once, with the value { start: 0, end: 1.7976931348623157e+308 }.

component.ts:

allTasks = new MatTableDataSource<Task>([]);

@ViewChild(MatTable) table: MatTable<any>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sorter: MatSort;

ngAfterViewInit() {
  this.allTasks.paginator = this.paginator;
  this.allTasks.sort = this.sorter;
  this.table.viewChange.asObservable().subscribe(val => {
    console.log(`${val.start} - ${val.end}`);
  });
}

component.html:

<mat-table
  matSort
  [dataSource]="this.allTasks"
>
...
</mat-table>
like image 883
JWess Avatar asked Jun 14 '18 20:06

JWess


People also ask

What is * matHeaderCellDef?

MatHeaderCellDef extends CdkHeaderCellDefHeader cell definition for the mat-table. Captures the template of a column's header cell and as well as cell-specific properties. Selector: [matHeaderCellDef]

What is multiTemplateDataRows?

multiTemplateDataRows have a different variable to hold the row's index called dataIndex . Access the row's index using let k = dataIndex . <!-- Row content--> <mat-row *matRowDef="let row; columns: displayedColumns; let k = dataIndex;" matRipple (click)="this.expandRow(row, k)"> </mat-row> Relevant github issue.


1 Answers

While Daniel solution works perfectly, I found something simpler.

this.allTasks.connect().value

will give you the rows displayed on the screen for the current page.

If you want all the filtered row (that might be displayed on several pages), you can also use:

this.allTasks.filteredData
like image 50
Tonio Avatar answered Oct 16 '22 09:10

Tonio