代码之家  ›  专栏  ›  技术社区  ›  user441058

在ag网格事件中引用“this”

  •  0
  • user441058  · 技术社区  · 7 年前

    在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 回复  |  直到 7 年前
        1
  •  10
  •   Pratik Bhat    6 年前

    列举你可以解决的各种方法 问题-
    1.箭头功能的使用:

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

    2.使用 绑定() :

    onRowSelected: this.onRowSelected.bind(this)
    如果您的 onRowSelected 组件,它仅用于该网格。

    3.ag电网的使用 context 网格选项:

    但是,如果您想跨多个网格共享一个函数,并假设在网格实用程序服务中有这个函数。

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

    在行选定 您可以使用以下方法访问上下文:
    const ctx = params.context.parentComponent 引用组件变量