Sarvesh Yadav
Sarvesh Yadav

Reputation: 2620

What exactly $event object do in Angular 2?

I am bit confused what exactly $event doing here and what is the difference between this 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) {
      }
    }

Upvotes: 48

Views: 67426

Answers (3)

Sayu Paudel
Sayu Paudel

Reputation: 1

it holds all the values of an event. Like if you give an input what was the input.

Upvotes: 0

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658007

$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.

Upvotes: 46

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

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

Upvotes: 2

Related Questions