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) { } }
The $event object often contains information the method needs, such as a user's name or an image URL. The target event determines the shape of the $event object. If the target event is a native DOM element event, then $event is a DOM event object, with properties such as target and target.
Angular includes $event that contains the information about an event. The type of $event depends on the target event, e.g., if the target event is a native DOM element event, then it is an object. A component should define the onShow(event) method where the type of the parameter can be KeyboardEvent, MouseEvent, etc.
In Angular 8, event binding is used to handle the events raised by the user actions like button click, mouse movement, keystrokes, etc. When the DOM event happens at an element(e.g. click, keydown, keyup), it calls the specified method in the particular component.
DOM events carry a payload of information that may be useful to the component. This section shows how to bind to the keyup event of an input box to get the user's input after each keystroke.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With