18

I'm not sure is it question related to Angular 2 or more to Typescript itself. But anyway, I have a component which emits object

<grid" (gridButtonClickEvent)="gridEvent($event)"></grid>

Here is how I catching the event

private gridEvent(event) {
    console.log(event);
}

Here is the the event format of what I'm getting.

{Key: value}

So basically it's a simple object. I want to call a function with name Key and pass a value as an argument, how is it possible? The object Key would be different, but I know all possible variants and already registered function in my component.

private Key() {}

I was trying something like this

private gridEvent(event) {
    let eventName = Object.keys(event)[0];
    window[eventName]();
}

But it says

window[eventName] is not a function
1
  • 1. Do you have this event as a property on your window? 2. Why would you do things like that? Isn't that simpler to just pass a function as an object property? Commented Feb 8, 2017 at 9:00

1 Answer 1

46

Try this:

private gridEvent(event) {
    let methodName = Object.keys(event)[0];
    if(this[methodName]) {
        // method exists in the component
        let param = event[methodName];
        this[methodName](param); // call it
    }
}

More intuitive way would be to construct your emitting object as:

{ methodName: 'method1', methodParam: someValue } 

Then in the component:

private gridEvent(event) {
    let methodName = event.methodName;
    if(this[methodName]) {
        // method exists on the component
        let param = event.methodParam;
        this[methodName](param); // call it
    }
}

However, I'd personally avoid doing it this way if not really necessary. Rather emit an action that should be triggered and then do some switch statement to call the appropriate method instead. A dumber approach, but easier to reason about I'd say.

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

1 Comment

Really useful and simple solution. Works like a charm in Angular 6. Thank you!

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.