By Gary simon - Apr 05, 2017
When a user interacts with your app, it's sometimes necessary to know when this happens. A click, hover, or a keyboard action are all events that you can use to call component logic within Angular.
That's what Angular event binding is all about. It's one-way data binding, in that it sends information from the view to the component class. This is opposite from property binding, where data is sent from the component class to the view.
In this tutorial, let's take a closer look at property binding and how it works.
Be sure to Subscribe to the Coursetro Youtube Channel for more awesome development videos!
Whenever you wish to capture an event from the view, you do so by wrapping the event in question with ( ) parenthesis.
Angular provides you with a variety of events from which you can call component logic.
Here are examples of the most common events that you can use for event binding:
(focus)="myMethod()" // An element has received focus
(blur)="myMethod()" // An element has lost focus
(submit)="myMethod()" // A submit button has been pressed
(scroll)="myMethod()"
(cut)="myMethod()"
(copy)="myMethod()"
(paste)="myMethod()"
(keydown)="myMethod()"
(keypress)="myMethod()"
(keyup)="myMethod()"
(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"
(click)="myMethod()"
(dblclick)="myMethod()"
(drag)="myMethod()"
(dragover)="myMethod()"
(drop)="myMethod()"
Plus much more from the Event reference at Mozilla.org.
In our component template, let's create a button with a click event binding:
<button (click)="myEvent($event)">My Button</button>
Notice $event? It's optional, and it will pass along a variety of event properties associated with that particular event.
In the component class, let's create the myEvent() method:
export class AppComponent {
myEvent(event) {
console.log(event);
}
}
If you run ng serve in the console of the project, visit localhost:4200 in the browser, and click the button, you'll see a large object with a variety of properties that we can use in our method. In Chrome, just hit CTRL-SHIFT-I to see the console and the resulting console.
Try changing the (click) event to a different event from the list above or the Event reference page from Mozilla.org. You will find that you now have a large variety of user-initiated events from which you can make your Angular app responsive.