首页 > 解决方案 > 用于单元格渲染器的 Angular ag-grid 库父子通信

问题描述

我已经在我的角度代码中实现了以下演示,并在我实现的代码中得到了错误。

app.component.ts

import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';
import { rowEditComponent } from "./row-edit-component";

@Component({
  selector: "my-app",
  template: `
<div style="height: 100%; box-sizing: border-box;">
    <ag-grid-angular
    #agGrid
    style="width: 100%; height: 100%;"
    id="myGrid"
    class="ag-theme-balham"
    [columnDefs]="columnDefs"
    [rowData]="rowData"
    [editType]="editType"
    [frameworkComponents]="frameworkComponents"
    (gridReady)="onGridReady($event)"
    (cellClicked)="onCellClicked($event)"
    [defaultColDef] = "defaultColDef"
    [immutableColumns] = "true"
    suppressClickEdit
    ></ag-grid-angular>
</div>
`
})
export class AppComponent {
  private gridApi;
  private gridColumnApi;

  private columnDefs;
  private rowData;
  private context;
  private frameworkComponents;
    private editType;
    private defaultColDef;

  constructor() {
    this.columnDefs = [
      {
        headerName: "Row",
           editable: true,
        field: "row",
        width: 150
      },
      {
        headerName: "value1",
        field: "value1",
        editable: true,
        width: 150
      },
      {
        headerName: "value2",
        field: "value2",
           editable: true,
        width: 150
      },
      {
        headerName: "value3",
        field: "value3",
           editable: true,
        width: 150
      },
      {
        headerName: "Currency (Pipe)",
        field: "currency",
           editable: true,
        width: 100
      },
      {
        headerName: "Actions",
        field: "action",
        cellRenderer: "rowEditCRenderer",
        cellRendererParams: {
          cancelOtherRowEditors: this.cancelOtherRowEditors.bind(this)
        },
        width: 180
      }
    ];
    
    this.rowData = createRowData();
    this.editType = "fullRow";
    
    this.frameworkComponents = {
    rowEditCRenderer: rowEditComponent
   
    };
    
    this.defaultColDef = {
            sortingOrder: ["asc", "desc"],
            stopEditingWhenGridLosesFocus: false,
            sortable:true,
            enableFilter: true,
            suppressKeyboardEvent: function (event) {
                if(!event.editing || event.event.code === "Enter")
                return true;
            }
        };
  }

  cancelOtherRowEditors(currentRowIndex) {
    const renderers = this.gridApi.getCellRendererInstances();
    renderers.forEach(function(renderer) {
      if(!renderer._agAwareComponent.isNew && 
        currentRowIndex !== renderer._params.node.rowIndex) {
        renderer._agAwareComponent.onCancelClick();
      }
    });
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

  }

  onCellClicked(params) {
    if(params.node.field !== 'action') {
      this.cancelOtherRowEditors(params.node.rowIndex);
    }
  }
}

function createRowData() {
  var rowData = [];
  for (var i = 0; i < 15; i++) {
    rowData.push({
      row: "Row " + i,
      value1: i,
      value2: i +10,
        value3: i +30,
      currency: i + Number(Math.random().toFixed(2))
    });
  }
  return rowData;
}

app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { FormsModule } from "@angular/forms"; // <-- NgModel lives here
// HttpClient
import { HttpClientModule } from "@angular/common/http";

// ag-grid
import { AgGridModule } from "ag-grid-angular";
import { AppComponent } from "./app.component";


import { rowEditComponent } from "./row-edit-component";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule, // <-- import the FormsModule before binding with [(ngModel)]
    HttpClientModule,
    AgGridModule.withComponents([rowEditComponent])
  ],
  declarations: [AppComponent, rowEditComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

行编辑组件.ts

import {ICellRendererAngularComp} from "ag-grid-angular";

@Component({
    selector: 'child-cell',
    template: `
    <button type="button" *ngIf="isNew == true" (click) = "onEditClick()" data-action-type="view" class="btn btn-default">
               Edit
             </button>

             <button type="button"  *ngIf="isNew == false" (click) = "onUpdateClick()" data-action-type="view" class="btn btn-default">
               Update
             </button>

             <button type="button" *ngIf="isNew == false" (click) = "onCancelClick()" data-action-type="view" class="btn btn-default">
               Cancel
             </button>

            <button type="button"  *ngIf="isNew == true" (click) = "onDeleteClick()" data-action-type="remove" class="btn btn-default">
               Delete
            </button>`,
    styles: [
        `.btn {
            line-height: 0.5
        }`
    ]
})
export class rowEditComponent implements ICellRendererAngularComp {
    public params: any;
    public isNew: any;
    agInit(params: any): void {
        this.params = params;
    }
    
     constructor() {
        this.isNew = true;
    }

    public invokeParentMethod() {
        this.params.context.componentParent.methodFromParent(`Row: ${this.params.node.rowIndex}, Col: ${this.params.colDef.headerName}`)
    }

    refresh(): boolean {
        return false;
    }
    
    onEditClick() {
      const index = this.params.node.rowIndex;
      this.params.cancelOtherRowEditors(index);
      this.isNew = false;
      this.previousData = JSON.parse(JSON.stringify(this.params.node.data));
      let cols = this.params.columnApi.getAllGridColumns();
      let firstCol = {
          "colId": ""
      }
      if (cols) {
          firstCol = cols[0];
      }
      let rowIndex = this.params.node.rowIndex;
      this.params.api.setFocusedCell(rowIndex, firstCol.colId);
      this.params.api.startEditingCell({
          rowIndex: rowIndex,
          colKey: "row"
      });
    }

    onUpdateClick() {
        this.isNew = true;
        let obj: any = {};
        obj.type = "update";
        this.params.api.stopEditing();
        obj.selectedData = [this.params.data];
        // update logic ....
    }

    public onCancelClick() {
        this.isNew = true;
        this.params.node.setData(this.previousData);
        this.params.api.stopEditing(true);
    }
    
    onDeleteClick() {
      const selectedData = [this.params.node.data];
      console.log(selectedData);
      this.params.api.applyTransaction({ remove: selectedData });
    }
}

在我的本地环境和 plunkr 演示中出现以下错误,它工作正常,由其他用户开发

renderer._agAwareComponent.onCancelClick 不是 app.component.ts 中的函数

我尝试了所有可能的方法,但没有成功。我从过去的 2-3 天开始苦苦挣扎。请帮我解决这个问题

标签: angularag-gridag-grid-angular

解决方案


推荐阅读