Angular 2: calling a function from a string name

I'm not sure if the question is related to Angular 2 or more with Typescript. But anyway, I have a component that emits an object

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

This is how I caught the event

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

Here is the event format that I get.

 {Key: value} 

So basically this is a simple object. I want to call a function called Key and pass a value as an argument, how is this possible? The Key object will be different, but I know all the possible options and an already registered function in my component.

 private Key() {} 

I tried something like this

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

But he says

 window[eventName] is not a function 
+6
source share
1 answer

Try the following:

 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 } } 

A more intuitive way would be to create your own radiating 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 } } 
+11
source

Source: https://habr.com/ru/post/1014793/


All Articles