Search code examples
angularag-grid-angular

How to get only visible rows in ag grid? - Angular


I am using ag-grid as a data grid framework in my angular application. I could not find any api to get only visible rows. Meaning the rows which are visible on the screen and which do not include rows hidden because of scroll.


Solution

  • I did find a way to get the visible rows using below, little dirty code (please read comments for the details) -

    // skipping the component decorator and template details
    export class GridComponent {
      api: GridApi;
      rowHeight = 48;
      gridBodyHeight;
      scrollPosition = 0;
      visibleRowNodes = []; // this variable holds the visible rows at any moment during the grid's existence
    
      constructor(private elementRef: ElementRef) {}
    
      public gridReady(params: GridReadyEvent) {
        this.api = params.api;
        const headerElement = this.elementRef.nativeElement.querySelectorAll('.ag-header');
        const agGrid = this.elementRef.nativeElement.querySelectorAll('ag-grid-angular');
        this.gridBodyHeight = agGrid[0].offsetHeight - headerElement[0].offsetHeight;
        this.rowHeight = this.api.getDisplayedRowAtIndex(0) ? this.api.getDisplayedRowAtIndex(0).rowHeight : this.rowHeight;
        this.handleModeUpdateAndScrollEvent();
        // below call is need to get the visible rows when grid is ready
        this.visibleRowsChange.next({ top: this.scrollPosition });
      }
    
      // the visible rows only gets changed on
      // modelUpdated and bodyScroll events
      private handleModeUpdateAndScrollEvent() {
        this.gridOptions.onBodyScroll = (event) => {
          if (event.direction === 'vertical') {
            this.scrollPosition = event.top;
            this.visibleRowsChange.next(event);
          }
        };
        this.gridOptions.onModelUpdated = (event) => {
          this.visibleRowsChange.next({ top: this.scrollPosition });
        };
    
        this.visibleRowsChange
          .pipe(debounceTime(1000))
          .subscribe(v => {
            const topIndex = v.top / this.rowHeight;
            const bottomIndex = ((v.top + this.gridBodyHeight) / this.rowHeight) + 1;
            this.visibleRowNodes = this.api.getRenderedNodes().filter(node => node.rowIndex >= topIndex && node.rowIndex <= bottomIndex);
            console.log(this.visibleRowNodes);
          });
      }
    }