0

Is it possible to get the function passed to the Event Emitter?

I have a component and i pass a function to an event emitter like this:

<component (onClick)='function(parameter)'></component>

and in my Component i have the @Output to recieve the function and to emit when click like this:

@Output() onClick: EventEmitter<any> = new EventEmitter<any>();
<button (click)="onClick.emit($event)">

The thing is that i would like to get the function that i pass to the component, is it possible?

Hely Saul Oberto
  • 577
  • 1
  • 10
  • 22

2 Answers2

0

Yes that is possible

Lets say you have a add function inside your child component.

  @Output() onClick: EventEmitter<any> = new EventEmitter<any>();

  public add(a: number, b: number): number {
    return a + b;
  }

And on the buttons click event, you can emit the function

 <button (click)="onClick.emit(add)">Add</button>

Inside your parent component you can listen on the events from the child component.

 <component (onClick)='someFunc($event)'></component>

and call the function when the event is triggered.

someFunc(add: any) {
  const result = add(5, 5);
  console.log('and result is',result);
}
Kasper Due
  • 699
  • 7
  • 19
0

try like this :

<component (onClick)='function($event)'></component>

instead of

<component (onClick)='function(parameter)'></component>

Chandru
  • 10,864
  • 6
  • 38
  • 53