Hi everyone. In this tutorial, I’m gonna talk about Event Binding and References topic in Angular 2.
Event Binding means that some actions occur in view and these actions trigger our components. Now, let’s define a button in template attribute of our component.
In our template attribute of our component, we defined a button and defined an event between parenthesis. In Angular 2, when we use events, we defines it between parenthesis like (click). Here, we defined a click event that is triggered when button clicks. Also, we assigned the clickEvent() method to this event. When we clicked the button, The Button Clicked! text will be written to browser’s console.
After I opened browser console and clicked the button, I could see the text.
Now, let’s take a look at the References topic.
I developing web applications with Angular 2, we need to pass element values to our components and In Angular 2, References is easy.
We will change template of our component and clickEvent() method. Like this:
- we added an input tag to our template and defined it with #inputTag expression. When we use References in Angular 2, we define our reference with # and then use it in where we want. Here, we passed it’s value to clickEvent method by using inputTag.value expression.
- We also changed clickEvent method that accepts a value to write console. When we click the button, the value of input (#inputTag) will be passed to this method that writes the value to the console.
I opened main page, entered a text, clicked the button and checked the console of browser.
Well, what happens when we send only inputTag instead of inputTag.value to the clickEvent method?
If we do this, reference element will be sent to clickEvent method instead of it’s value. Like this screen output:
When we wat to detect or send the event type to our method, we can use $event expression. Now, change the template attribute like this:
In this template attribute, when the mouse come on the button, event type will be sent to clickEvent method and clickEvent method will write that to console.
In this tutorial, we learnt
- Event Binding
- Reference Value
- Reference Element
- Event From Reference Element
Until the next article, take you care.
With Greetings And Love