Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {       }     } 
like image 255
Sarvesh Yadav Avatar asked Jun 21 '16 12:06

Sarvesh Yadav


People also ask

What does $event do in Angular?

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.

What type is $event Angular?

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.

What is $event Angular 8?

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.

What is DOM event in Angular?

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.


1 Answers

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

like image 176
Günter Zöchbauer Avatar answered Sep 21 '22 08:09

Günter Zöchbauer