简体   繁体   中英

How do I synchronize the scroll of two data table contents together (ag-grid)

I am using ag-grid in Angular and I want to have two data table (ag-grid) one below the other.

The content of both the data table should move together, when I make a scroll in table 1 or table 2. That is the scroll of both the data table should be synchronized.

The HTML for the same is as below:

<div>
<div id="grid-wrapper">
    <ag-grid-angular #agGrid1 id="myGrid1" class="ag-theme-balham" [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef" [rowData]="rowData"></ag-grid-angular>
</div>
<div id="grid-wrapper">
    <ag-grid-angular #agGri2 id="myGrid2" class="ag-theme-balham" [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef" [rowData]="rowData"></ag-grid-angular>
</div>
</div>

Component code:

this.agGrid1._nativeElement.onscroll = function() {
  this.agGrid2._nativeElement.scrollTop=this.agGrid1._nativeElement.scrollTop;
}
this.agGrid2._nativeElement.onscroll = function() {
  this.agGrid1._nativeElement.scrollTop=this.agGrid2._nativeElement.scrollTop;
}

I have tried the scenario in stackblitz . But I was not able succeed. But tried similar scenario in case of two divs and its working for the same. Below is the POC that i tried:

https://stackblitz.com/edit/angular-ag-grid-common-scroll?file=src%2Fapp%2Fapp.component.ts

https://angular-ag-grid-common-scroll.stackblitz.io

Ag-grid has Aligned grids for exactly the same requirement as yours. Having aligned grids will not just synchronize scrolling but also column order, width and visibility.

As per docs -

Aligning two or more grids means columns will be kept aligned in all grids. In other words, column changes to one grid (column width, column order, column visibility etc) are reflected in the other grid. This is useful if you have two grids, one above the other such that their columns are vertically aligned, and you want to keep the columns aligned.

You should be able to do it like this -

gridOptionsFirst = {
    // some grid options here
        ...
};

gridOptionsSecond = {
    // register first grid to receive events from the second
    alignedGrids: [gridOptionsFirst]

    // other grid options here
    ...
}

Detailed example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM