在 ag-grid 事件中引用 'this'
referencing 'this' in ag-grid events
在农业网格事件中,例如onRowSelected(), 'this' 引用网格对象。但是,我需要引用组件变量,但不知道如何引用。我所做的是这个,但它是一个 hack:
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.Use of ag-grid context
gridOption:
但是,如果您想在多个网格之间共享一个功能,假设在网格实用程序服务中具有此功能。
然后你可以使用下面的方法。在 gridOptions 中,使用上下文选项
gridOptions = { context : {parentComponent: this}...}
和 onRowSelected: this.gridUtilityService.onRowSelected
在 onRowSelected
中,您可以使用 :
访问上下文
const ctx = params.context.parentComponent
引用组件变量
在农业网格事件中,例如onRowSelected(), 'this' 引用网格对象。但是,我需要引用组件变量,但不知道如何引用。我所做的是这个,但它是一个 hack:
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.Use of ag-grid context
gridOption:
但是,如果您想在多个网格之间共享一个功能,假设在网格实用程序服务中具有此功能。
然后你可以使用下面的方法。在 gridOptions 中,使用上下文选项
gridOptions = { context : {parentComponent: this}...}
和 onRowSelected: this.gridUtilityService.onRowSelected
在 onRowSelected
中,您可以使用 :
访问上下文
const ctx = params.context.parentComponent
引用组件变量