Akshay Rana Akshay Rana - 1 month ago 17
AngularJS Question

Ag-grid(Angular 2) Cannot access component fields in CellRenderer

I'm facing this issue while trying to call a service method on the click event of a button that is created using cellRenderer.

I'm using ag-grid with Angular2.

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


I'm getting the following error :

EXCEPTION: Cannot read property 'getAll' of undefined


Also, I'm not able to access any of my Component variables.

Answer

cellRenderer is in different context, so this is not accessible in updateRecord function.

You need to initialize context parameter in gridOptions and use it in params object.

set context in your gridOptions object in this way

this.gridOptions.context = {
            myService: this.myService
        } 

Your myService will be available in context property.

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