<button (click)="doSomething()">Do it</button>
I used the above syntax lots of times, almost daily.
But how does Angular know how to deal with this (click)
thing?
It seems to work with any element, even custom Angular components. So how does this work?
It works because of the so called Event Biding. Basically it binds the target event name (click) to a method from the component (doSomething).
As explained in this nice article , Angular doesn't have a list of it's own event names, but it actually uses the names of the underlying DOM events.
So the event binding part of the <button (click)="doSomething()">Do it</button>
snippet is the equivalent of this vanilla snippet:
element.addEventListener('click', () => { doSomething() });
This means the if I want to know which events I can bind to in Angular I can search them here: https://developer.mozilla.org/en-US/docs/Web/Events
What about the $event
?
If the event is a DOM event, like click, mouseenter, keyup etc then the $event
is the event itself. For example in the case of click
, the $event is a MouseEvent
.
But for custom events (using the EventEmitter) the $event
is actually the emitted data.
Top comments (0)