What is the $ event object in Angular 2?

I'm a little confused what exactly $ event does here and what is the difference between these two examples

<button (click)="clicked($event)"></button> @Component(...) class MyComponent { clicked(event) { event.preventDefault(); } } 

and

 <button (click)="clicked()">Click</button> @Component(...) class MyComponent { clicked(event) { } } 
+6
source share
2 answers

$event is the event itself.

Event binding (someevent) allows you to bind DOM events and EventEmitter events. The syntax is exactly the same.

For DOM $event events, there is a MouseEvent , KeyboardEvent or an event value like any event you are listening to.

For EventEmitter events EventEmitter emitted value is available as $event

Assuming this $event example refers to an emitted instance of a Ferrari car:

 @Output() carChange:EventEmitter<Car> = new EventEmitter<Car>(); someMethod() { this.carChange.emit(new Car({name: 'Ferrari'})); } 

If you are not using $event , as in (click)="clicked()" , then the event value is not passed.

Actually, as far as I remember, it is still transmitted in some browsers, but not in all (I don’t remember which ones)

But if you use the Angulars WebWorker function, then your method may not receive a fired or fired event if you do not explicitly list it.

+10
source

If you do not pass $event in your template, you will not have the $event variable in your available clicked() method.

See Plunker for a quick comparison.

+3
source

All Articles