What exactly $event object do in Angular 2?
Solution 1:
$event
is the event itself.
The event binding (someevent)
allows to bind to DOM events and to EventEmitter
events. The syntax is exactly the same.
For DOM events $event
is the MouseEvent
, KeyboardEvent
, or the event value of the type of whatever event you listen to.
For EventEmitter
events the emitted value is available as $event
Assuming this example $event
refers to the emitted Ferrari
car instance:
@Output() carChange:EventEmitter<Car> = new EventEmitter<Car>();
someMethod() {
this.carChange.emit(new Car({name: 'Ferrari'}));
}
If you don't use $event
like in (click)="clicked()"
then the event value is not passed.
Actually as far as I remember it is still passed in some browsers but not in all (don't remember which ones)
But if you use Angulars WebWorker feature, then your method might not get the fired or emitted event if you don't explicitely list it.
Solution 2:
If you don't pass the $event
in your template, then you won't have the $event
variable in your clicked()
method available.
See this Plunker for a quick comparison