Search code examples
angularangular-event-emitter

Event Emitter Binding


I am going through "Angular Up and Running" by Shyam Seshadri, published by O'Reilly. In the discussion on Output and the emitting of events I'm a little confused.

The EventEmitter in a component is declared, initialized and implemented as:

@Output() private toggleFavorite: EventEmitter<Stock>;

constructor() {
 this.toggleFavorite = new EventEmitter<Stock>();
}

onToggleFavorite(event) {
 console.log('We are toggling the favorite state for this stock.', event);
 this.toggleFavorite.emit(this.stock);
}

The binding in the app.component.html reads:

(toggleFavorite)="appToggleFavorite($event)"

But the method in app.component.ts is defined as:

appToggleFavorite(stock: Stock) {
 console.log('Favorite for stock ', stock, ' was triggered.');
}

If the binding is passing the $event object, and the bound method is expecting a Stock type, why does this work?

(And it does work, I've tested it.)

I am not asking what the $event object does, I already know that. Please re-read my question above carefully. I am asking: when a bound function is expecting a typed parameter, why is a binding to an EventEmitter object passing the $event object instead of an object of the expected type, and why does it seem to work (the parameter gets it's values as typed.)


Solution

  • Technically, the $event is unecessary and create confusion.

    (toggleFavorite)="appToggleFavorite()"
    

    will work as well, since you're implying that when you call .emit, you will call appToggleFavorite with any value type given to .emit. And Javascript is an untyped language, so it will work at run time.