Angular 6 MatTable Performance in 1000 rows.

前端 未结 7 816
無奈伤痛
無奈伤痛 2020-12-03 04:56

I\'m using angular material in my project and I\'m using Mat-Table to render 1000 Product/row per table. When Change pagination (we use backend pagination) of table to 1000

7条回答
  •  北海茫月
    2020-12-03 05:41

    To extend upons @Turneye 's answer. The reason it's happening is because the paginator is being set after all the rows have been rendered, because that's what the ngAfterViewInit hook tells you.

    So it first renders all rows from data source, then it sees: "hey, I'm getting a paginator, let me just remove all the rows (except the pager count)". This is obviously very slow on large data sets and/or complex table cell templates.

    You can solve this by using the {static: true} option on your @ViewChild. This will make the paginator available inside the ngOnInit lifecycle hook, and before any row has been rendered:

    To steal his code, you can change it to this, and still have a fast table:

    readonly dataSource: MatTableDataSource = new MatTableDataSource();
    
    @ViewChild(MatSort, { static: true }) sort: MatSort;
    @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
    
    ngOnInit() {
      this.dataSource.data = [ GetLargeDataSet ];
      this.dataSource.sort = this.sort;
      this.dataSource.paginator = this.paginator;
    }
    

    Be aware though that this will not work if your mat-paginator is inside a structural directive like *ngIf


    Another performance issue could be that you have to declare a trackBy function:

    To improve performance, a trackBy function can be provided to the table similar to Angular’s ngFor trackBy. This informs the table how to uniquely identify rows to track how the data changes with each update.

    提交回复
    热议问题