0

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

3
  • Maybe you could make use of Generics types ? something like action<T>: (object: T, ...params: any[]) => any; Commented Dec 10, 2019 at 15:40
  • how would it actually inform about the current instance, not the type, of the component? Commented Dec 10, 2019 at 15:44
  • Well, if you set the generic type of your action function to be the current component ( when you call it ) . The object parameters will be of the type of the current component. Commented Dec 10, 2019 at 15:46

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

I think all you needed is bind

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.