Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Call function from a string name

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
like image 249
Lunin Roman Avatar asked Feb 08 '17 08:02

Lunin Roman


1 Answers

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.

like image 155
seidme Avatar answered Nov 08 '22 13:11

seidme