Search code examples
angularng2-smart-table

Angular 4 , 'this' is undefined when using callback 'onComponentInitFunction' function of ng2-smart table


I am using ng2-smart-table in my component.

I am trying to invoke the parent component's approveTheOrder() method but I am unable to get the object of the parent class

Below is the snippet

{
  title: "Actions",
  type: "custom",
  renderComponent: ActionRenderComponent,
  onComponentInitFunction(instance) {
    instance.actionEmitter.subscribe(row => {
      if(row == CONSTANT.STATUS_APPROVE){
        //here 'row' value is from childComponent-ActionRenderComponent,which I am able to get easily in parentComponet 
       this.approveTheOrder(instance.rowData.id); // here this is undefined, 

      }
      if(row == CONSTANT.STATUS_REJECT){
        this.rejectOrder();//this is undefined
      }
      if(row == CONSTANT.STATUS_PENDING){
        this.pendingOrder(); // this is undefined
      }
    });
  },

  filter: false
};

Does anyone have any idea how to get the 'this' in the below onComponentInitFunction() ?

Below is the image of the error that I am getting.enter image description here

Also I tried to use 'bind' function was unsuccessful in achieving the goal, Could anyone please guide me here, I am really stuck at this point.

EDIT 1 Note that I am able to get event from ChildComponent in the parentComponent, but the problem here is specific to ng2-smart-table component.

To get the value from ChildComponent, I am trying to use in-build callback function onComponentInitFunction(instance) of ng2-smart-table component


Solution

  • The following syntax:

    {
      onComponentInitFunction(instance) {
        ...
    

    will be transformed to function expression:

    {
      onComponentInitFunction: function(instance) {
        ...
    

    You should use arrow function to retain this:

    onComponentInitFunction: (instance) => {