Igino Boffa
Igino Boffa

Reputation: 736

Get element instance in callback function

I am developing an Angular library, a sort of Angular wrapper for Golden Layout. I created an interface, called ActionItem, that gives the possibility to add buttons with actions in the component tab:

export interface ActionItem {
    label: string;
    icon?: string;
    iconColor?: string;
    action: (...params: any[]) => any;
}

The problem is, as I use this interface in another interface, that I use to define the structure of the component (GoldenLayout component, not the Angular one) within the application, I don't know how to inform the action about the current instance of the component.

By the moment, I only managed to add an instanceId attribute to the resulting button, having the component (the Angular one this time) mapped by this value inside the library service. But I can't figure out how to "inject" this value inside the listener I define in action

Upvotes: 0

Views: 261

Answers (1)

Igino Boffa
Igino Boffa

Reputation: 736

Seems I solved: not the most elegant solution maybe, but it works.

I changed the action type to Function

In the service, where I create the button, I did this:

const _action = item.action.bind(component.instance);
 actionBtn.addEventListener('click', _action, false);

where item is ActionItem itself and component is the ComponentRef object representing the object being created.

In this way, defining in my application the (GoldenLayout) Component in this way:

 {
  ...
  component: Test1Component as Component,
  ...
  tabActions: [
    {
      label: 'Test',
      icon: 'fa fa-heart',
      action: function () { console.log(this) }
    } as ActionItem
  ]
}

this will refer to the component instance. Hope it helps someone else

Upvotes: 0

Related Questions