Eric Hewett
Eric Hewett

Reputation: 557

ag-grid rendering causes service component initiated from event to be undefined

I am using ag-grid. Please can someone explain this: if I have a method to prepare GridOptions in which I setup an onCellValueChanged event. This calls a service component to access the database, which also used to populate the data. The service component when the event is activated is undefined. If I move the event declaration to the html template it fires the event and the service component is defined.

So the event defined in the html template works

      <ag-grid-angular #agGridProject class='ag-theme-bootstrap' style="width:100%; height: 650px;" [gridOptions]="gridOptions"
    (cellValueChanged)="onCellValueChanged($event)"></ag-grid-angular>

This does not:

      private prepareGrid() {
        this.gridOptions = <GridOptions>{
          columnDefs: this.ColumnDefs,
          enableSorting: true,
          enableFilter: true,
          rowSelection: 'single',
          rowHeight: 22,
          animateRows: true,
          pagination: true,
          enableColResize: true,
          // onCellValueChanged: this.onCellValueChanged,
          onGridReady: this.onGridReady,
          context: {
            componentParent: this
          }
        };

The method fired by the event containing the service:

  private onCellValueChanged(params: any) {
    const projectData = params.data;
    console.log(params.data);
    const model = new UpdateProjectRequest(projectData.firmId, projectData.description, projectData.notes);
    console.log(new Date().toUTCString(), projectData.id, model);
    const e = this.stratoApiProjectService;
    this.stratoApiProjectService.updateProject(projectData.id, model);
  }

I suspect the issue is caused by the Typescript pre-processor or maybe I have a bug, but please can someone explain?

Upvotes: 0

Views: 790

Answers (1)

Pratik Bhat
Pratik Bhat

Reputation: 7614

When you are registering onCellValueChanged with grid options you need to ensure your component context is passed along like this -

 onCellValueChanged: this.onCellValueChanged.bind(this),

In your current setup, this inside onCellValueChanged refers to its own scope instead of component scope.

More on this here

Upvotes: 2

Related Questions