I want to make my ag-grid dynamically resize as the window width is changed as well as to destroy the FromEvent when the user leaves.
import { Component, Input, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { AgGridAngular } from 'ag-grid-angular';
import {
ColDef,
ColumnApi,
GridApi,
GridOptions,
GridReadyEvent,
IDatasource,
IGetRowsParams,
RowClickedEvent,
} from 'ag-grid-community';
import { debounceTime, fromEvent, ReplaySubject, Subject, takeUntil } from 'rxjs';
export class Component implements OnInit, OnDestroy {
private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);
@ViewChild(AgGridAngular)
agGrid: AgGridAngular;
public gridOptions: GridOptions = {
...,
onGridReady: this.onGridReady,
};
private gridApi: GridApi;
private columnApi: ColumnApi;
constructor() {
console.log('Construct');
}
ngOnDestroy(): void {
this.destroyed$.next(true);
this.destroyed$.complete();
}
onGridReady(params: GridReadyEvent) {
console.log('gridReady', this.destroyed$);
this.gridApi = params.api;
this.columnApi = params.columnApi;
fromEvent(window, 'resize')
.pipe(debounceTime(200), takeUntil(this.destroyed$))
.subscribe(() => {
console.log('Window resizing');
this.gridApi?.sizeColumnsToFit();
});
params.api.setDatasource(this.dataSource);
params.api.sizeColumnsToFit();
}
}
The private destroyed variable prints as:
{
"closed": false,
"currentObservers": null,
"observers": [],
"isStopped": false,
"hasError": false,
"thrownError": null,
"_bufferSize": 1,
"_windowTime": null,
"_timestampProvider": {},
"_buffer": [],
"_infiniteTimeWindow": true
}
inside the onInit but prints as undefined
inside of the onGridReady event that causes an error in the browser:
ERROR TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable
In your GridOptions
, you'll need to bind this
to the function, like so:
public gridOptions: GridOptions = {
onGridReady: this.onGridReady.bind(this),
};
although, if you prefer, this would also likely work:
public gridOptions: GridOptions = {
onGridReady: (event) => { this.onGridReady(event); },
};