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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With