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,
- Architecture Angular 2 Part: 1
- Getting Started with Angular 2 Part: 2
- Understanding Application Files in Angular 2 Part: 3
- Simple Hello world Application in Angular 2 Part: 4
- Creating our first component in Angular 2 Part: 5
- Style Components in Angular 2 Part: 6
- Date Binding in Angular 2 Part: 7
- Class & Style Binding in Angular 2 Part: 8
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
- @Component({
- selector: "my-tuts",
- template: `<h2>{{title}}</h2>
- <button>Click me</button>`
- })
Just like how we have square brackets for property binding, for event binding, proceed, as shown ().
- <button(click)="onClick()">Click me</button>;
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.
- onClick(){
- console.log('ButtonClicked');
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.
Now, in Angular, it is very easy to reference HTL tags or the elements. Now, to reference an element, all we need to do is use hash (#) symbol with any random variable, as shown below.

Sateeshkumar PasupuletiPosted May 9, 2017, 4:24 AM
Good & Pleasent #Article ,keep sharing like this.... 👌