3

在 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;
    }
  }

有没有更好的办法?

4

1 回答 1

10

列举你可以解决这个问题的各种方法 -
1.使用箭头函数:

   onRowSelected : (event: any) => { ... }

2. 使用bind()

onRowSelected: this.onRowSelected.bind(this)
onRowSelected如果您与您的组件紧密耦合并且它仅用于该网格,则 此方法很有用。

3.ag -grid contextgridOption的使用:

但是,如果您想在多个网格中共享一个功能,并且假设在网格实用程序服务中具有此功能。
然后你可以使用下面的方法。在 gridOptions 中,使用 context 选项

gridOptions = { context : {parentComponent: this}...}
onRowSelected: this.gridUtilityService.onRowSelected

onRowSelected您可以使用 : 访问上下文
const ctx = params.context.parentComponent以引用组件变量

于 2018-11-10T18:06:25.280 回答