You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$10
For Premium members:
This article enables you to understand event binding in Angular 2.
From our previous article, we learned about Class & Style binding, where the data flows from component to view. When component class property changes, the views also change.
I recommend you to go through my previous articles from the beginning for better understanding.
References,
In this article, we are going to learn Event Binding & Reference
Now, we are only setting the values to DOM element properties, but there is no way to retrieve DOM element properties.
For example There might be a situation, where the user will fill up a form or click a button, which results in flow of data from view to our components class. This is where event binding comes into the picture by helping us to capture the data flow from the view to the component.
In order to understand Event Binding better, let’s first create a button, as shown below.
Code
Just like how we have square brackets for property binding, for event binding, proceed, as shown ().
Let’s say there's a click event of a button. Whenever a click event is raised, let us call a method called OnClick.
In our class, let’s define the method, as shown below.
Save this and run it -- the output is as below,
When I click button for the first time, the log in the console looks, as shown below. For the second time, the count increases, as shown below.
ode
In order to get the data which is flowing from an input tag, we can use reference variable.
For example
Let’s say, we passed demoInput.value as one of the parameter to on click method.
Pass the value to onClick value and log the value, as shown below.
Save and run.
Key in some value say Hello world and watch in the console. It is going to log the input field, as shown below.
Key in some value say Hello world and watch in the console. It is going to log the input field, as shown above.
That is how Event binding happens; we have bound the button click event with handler called on click. We are going to use the reference to input the elements. By passing its value, we can retrieve the value in our class.
Finally to capture the event, we use $ event, as shown below.
Thank you for reading my article.
Happy coding.
AngularJS Recipes