Angular 5 Tutorial
Event Binding
In any application we work with data to show them and processing the data. We do this with help of events like mouse click event, keyboard key down event etc.. So here in this chapter we’ll learn about data binding and event binding in Angular.
Let’s see the event binding first. Event bindings helps us to interact with application. When ever user clicks mouse, press keyboard or other tasks then an event is generated and we have to handle that event.
Round brackets are used for event binding. In other way you can say that round brackets are used for input. Here is the basic structure of event handling:
(eventname)=”functionNameThatHaveLogicToHadleEvent()”
Let’s create a button and clicking on this button will simply tell us how many times that button is clicked. We will need to handle the click event of this button. Let’s add following code in dashboard.component.html file:
<p class="text-center">Click count is: {{count}}</p>
<button (click)="clickCount()">
Click Me!
</button>
Here we have a created a button having text click me. In the syntax you can see there is round bracket and inside it click is written. This says that we want to handle ‘click’ event. We write the event name inside the round bracket. You can see this event is assigned to a function ‘countClick()’. This is simple javascript function and whenever button will be clicked this function will be called. This function will be written in dashboard.component.ts file.
Also we have added code to show the number of clicks using string interpolation {{count}}.
At the top of dashboard.component.ts file, before constructor we will add a variable named ‘count’ which will hold value of the number of times button is clicked. Inside countClick function, we will just increase the value of count variable.
message: string;
count: number = 0;
constructor() { }
ngOnInit() {
this.message = "Learning Angular is exciting!";
}
clickCount(){
this.count +=1;
console.log("current count is " + this.count);
}
Now when we run the application, we will see output like this:
Here we can see the current count is zero. When we click the button, it will increase the number. This is very simple example of handling event in Angular.
In the same way we can handle other events like dropdown select event, form submit event etc. Everywhere in angular we handle application events using round brackets.
In next section we will learn about data binding.