9

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.

1 Answer 1

11

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;
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Worked perfectly fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.