Angular 6 MatTable Performance in 1000 rows.

前端 未结 7 800
無奈伤痛
無奈伤痛 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:51

    Large DataSet Observable Passed Down From Parent Component

    After much struggling, I was able to combine pieces of many different answers from this post, including @turneye's above and the OP's selected right answer, and also answers on another similar SO post, here and here.

    I had ~1000 rows that I needed for a parent component on the page, as well as several child components, including a paginated MatTable component.

    The data was loading in <500ms, but then the page would take, on average, 15 seconds to render, as originally I was just passing a MatTableDataSource object with the data already assigned.

    The solution:

    1. Pass an observable with the data, and then subscribe to it after the view initializes, setting the MatTableDataSource.data property after setting the MatPaginator and MatSort.
    2. Set changeDetection to ChangeDetectionStrategy.OnPush in the Component decorator config.
    3. After setting the MatDataSource.data property in the observable body, tell angular to detect changes with ChangeDetectorRef.detectChanges()

    Now the full DOM is rendered in ~1 second total, which is fine given the volume of data that needs to be present at once.

    Here's a stripped down example:

    @Component({
        changeDetection: ChangeDetectionStrategy.OnPush,
        selector: 'app-dynamic-grid',
        templateUrl: './dynamic-grid.component.html',
        styleUrls: ['./dynamic-grid.component.scss'],
      })
      export class DynamicGridComponent implements OnInit, AfterViewInit {
        @Input() public dataSource$: Observable<any[]>;
      
        public matDataSource = new MatTableDataSource<any>();
      
        @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
        @ViewChild(MatSort, { static: true }) sort: MatSort;
      
        constructor(private changeDetectorRef: ChangeDetectorRef) {}
      
        ngOnInit(): void {}
      
        ngAfterViewInit() {
          this.matDataSource.paginator = this.paginator;
          this.matDataSource.sort = this.sort;
      
          this.dataSource$.subscribe(x => {
            this.matDataSource.data = x;
    
            // The important part:
            this.changeDetectorRef.detectChanges();
          });
     
        }
    }
    
    0 讨论(0)
提交回复
热议问题