Ag-grid(Angular 2)无法访问CellRenderer中的组件字段

Aks*_*ana 9 ag-grid angular

我试图在使用cellRenderer创建的按钮的click事件上调用服务方法时遇到此问题.

我正在使用带有Angular2的ag-grid.

{ headerName: 'Update', field: "update", width: 80, cellRenderer : this.updateRecord }


updateRecord(params) {
    var eDiv = document.createElement('div');
    eDiv.innerHTML = '<span class="my-css-class"><button class="edit">Edit</button></span>';
    var eButton = eDiv.querySelectorAll('.edit')[0];
    eButton.addEventListener('click', function() {
      this.myService.getAll().subscribe(data => console.log(JSON.stringify(data)))
    });
    return eDiv;
  }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

EXCEPTION: Cannot read property 'getAll' of undefined
Run Code Online (Sandbox Code Playgroud)

此外,我无法访问任何我的组件变量.

Sef*_*efa 9

cellRenderer位于不同的上下文中,因此this无法在updateRecord函数中访问.

您需要初始化context参数gridOptions并在params对象中使用它.

以这种方式设置context在您的gridOptions对象中

this.gridOptions.context = {
            myService: this.myService
        } 
Run Code Online (Sandbox Code Playgroud)

myService将获得context房产.

updateRecord(params) {
    var eDiv = document.createElement('div');
    eDiv.innerHTML = '<span class="my-css-class"><button class="edit">Edit</button></span>';
    var eButton = eDiv.querySelectorAll('.edit')[0];
    eButton.addEventListener('click', function() {
      params.context.myService.getAll().subscribe(data => console.log(JSON.stringify(data)))
    });
    return eDiv;
  }
Run Code Online (Sandbox Code Playgroud)