在 ag-grid 事件中,例如onRowSelected(), 'this' 指的是网格对象。但是,我需要引用组件变量并且不知道如何。我所做的是这个,但它是一个黑客:
initializeGridOptions() {
this.gridOptions = {
columnDefs: [
{ headerName: "Core #", field: "coreNumber", width: 100, sort: 'asc' },
onRowSelected: this.onRowSelected,
}
this.gridOptions['_this'] = this; // HACK
}
onRowSelected(event: any) {
if (event.node.selected) {
(this as any)._this.selectedNode = event.node.data;
}
}
有没有更好的办法?
最佳答案
列举你可以解决的各种方法这个问题 -
1、箭头函数的使用:
onRowSelected : (event: any) => { ... }
2. 的使用绑定(bind)() :
onRowSelected: this.onRowSelected.bind(this)
如果您的 onRowSelected
紧密耦合到您的组件,它仅用于该网格。
3.ag-grid的使用
context
网格选项:但是,如果您想在多个网格之间共享一个功能,并且假设在网格实用程序服务中具有此功能。
然后你可以使用下面的方法。在 gridOptions 中,使用 context 选项
gridOptions = { context : {parentComponent: this}...}
和 onRowSelected: this.gridUtilityService.onRowSelected
在
onRowSelected
内您可以使用以下方式访问上下文:const ctx = params.context.parentComponent
引用组件变量
关于angular - 在 ag-grid 事件中引用 'this',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111132/