javascriptangularscopeag-gridag-grid-angular

Ag-grid cell editors with dynamic Parameters: use global variable


I just started to use ag-grid in one of my projects and I'm using "agSelectCellEditor" cell editor for two columns: "function" and "project_role". The select options for the project roles column depends on the function cell value.

This is the grid configuration:

<ag-grid-angular
        class="ag-theme-balham"
        style="height: calc(100% - 100px)"
        [defaultColDef]="demandsDefaultColDef"
        (gridReady)="onDemandsGridReady($event)"
        (cellValueChanged)="onDemandsCellValueChanged($event)"
        [frameworkComponents]="frameworkComponents"
      >
        <ag-grid-column headerName="Resource Description" headerClass="test">
          <ag-grid-column
            field="function"
            [cellEditor]="'agSelectCellEditor'"
            [cellEditorParams]="functionOptions"
            [sortable]="true"
            [pinned]="true"
            [width]="140"
          ></ag-grid-column>
          <ag-grid-column
            field="project_role"
            headerName="Project Role"
            [cellEditor]="'selectEditor'"
            [cellEditorParams]="projectRoleCellEditorParams"
            [sortable]="true"
            [pinned]="true"
            [width]="140"
          ></ag-grid-column>
 <ag-grid-angular/>

I followed the documentation to implement "Dynamic Parameters":

projectRoleCellEditorParams(params) {
    const selectedFunction = this.functions.find(x => x.name === params.data.function);
    const allowedProjectRoles = selectedFunction.projectRoles.map(x => x.name);
    return {
      values: allowedProjectRoles,
    };
  }

The problem is that "this" is undefined. I know that this is a problem that relates to the javascript scope. Somehow I need to provide "this" to the projectRoleCellEditorParams scope.

But how can I do this?


Solution

  • I found the answer by myself. You can use the context object.

    Set something to the context:

      onDemandsGridReady(params): void {
        this.demandsGridApi = params.api;
        this.demandsGridApi.context.functions = this.functions;
      }
    

    Use it in a function:

     const selectedFunction = params.api.context.functions.find(
          (x) => x.name === params.data.function
        );