ag-grid:对特定列使用网格事件 CellClicked - 无法访问 "this"

ag-grid: Using Grid Event CellClicked for specific column - cannot access "this"

我在网格中有一列,单击它时我试图访问 class 的某些方法,但 this 上下文已更改且不可用。 例如-

export class PreTflGridComponent implements OnInit {  

  columnDefs = [
    {onCellClicked: this.editCellClicked}
  ];

  constructor() { }   

  method(): void {
      console.log('working');
  }

  editCellClicked(params) {
    this.method();
  }  

}

错误:

ERROR TypeError: this.method is not a function

this 上下文更改后如何访问 methods/properties。

请参阅下面的确切问题 https://stackblitz.com/edit/angular-vwgcc2,如果您单击 make 列并打开控制台,那么它会显示我遇到的错误。

您应该使用具有简单逻辑的 cellRenderer 属性。对于复杂的逻辑渲染器,您应该使用 cellRendererFramework 更方便的方法:YourCustomRendererAngularComponent。

columnDefs = [
{
  headerName: 'Col Name',
  cellRendererFramwork: MyAngularRendererComponent, // RendererComponent suffix it is naming convention
  cellRendererParams: {
    onClick: (params) => this.click(params);  
  }
},
...
]

MyAngularRendererComponent 应该实现 AgRendererComponent。

同样在使用 MyAngualrRendererComponent 的 angular 模块中不要忘记放置此代码:

@NgModule({
 imports: [
   AgGridModule.withCompoennts([
      MyAngualrRendererComponent 
   ])
 ]
})

以上代码只是一小部分,完整示例请查看Stackblitz

this 似乎给了你实际的行。您需要做的是告诉您的 makeCellClicked 方法 this 实际上是什么,方法是将 this 绑定到它,例如:

onCellClicked: this.makeCellClicked.bind(this).

另请参阅您的 updated StackBlitz。