Event Binding in Angular
When a user performs some action such as pushing a button on the keyboard, clicking a link, and entering text, raise DOM (Document Object Model) events. Sometimes to respond to the user events we also need the data to flow in other direction i.e. from template to the class of a component. This article is basically about giving you an idea of how to bind those raised events to the component event handlers using the event binding syntax provided by Angular.
How to bind to the user input
Angular provided event bindings can be used to respond to the DOM events. Many of the DOM events are triggered when the user gives some input. Binding to those events just provides a way to fetch the data that the user has provided as input.
In order to bind to a DOM event, just surround the DOM event name in the parentheses followed by an assignment operator and a quoted template statement to it.
For example:
<button (click) = “onClick( )” > Greet </button>
The left-hand side of the assignment operator i.e. click identifies the click event of the button as the binding target. The quoted text is the template statement that responds on clicking by calling the onClick() method of the component.
Set properties on mouse click
Here we are setting some property to a mouse click event. We are binding to the click event and then setting a value of the property in the class of that component. For this, we are declaring a greeting property in the class just to show you how to do it and initially setting the value of that greeting property to an empty string and after clicking the button named ‘Greet’ it will have some value.
In the template of the component ( by use of interpolation ) :
@Component ({
selector : ‘app-test’;
template : `
<button (click)= “onClick( )” > Greet </button>
{{greeting}}
`
})
export Class TestComponent {
}
Here we have bound the greeting property(which is declared below) of the class to the template by use of interpolation ( It is basically {{some defined property}} bound by writing the defined property in double curly brackets in the template body. )
In the class of the component:
export class TestComponent {
public greeting=” “;
onClick( ) {
console.log(“Welcome”);
this.greeting=”Welcome”;
}
}
On clicking the greet button a message is displayed on the screen and in the console because of interpolation of this greeting property in the template.
Are you planning to boost the speed of your current app? We are an ERP Development Company that creates mobile apps that seamlessly improve app speed and performance. Get in touch with us for queries on event binding and avail our ERP development services NOW!
When we need data to flow from the template to the class of a component, we bind raised events to the component event handlers using the event binding syntax provided by Angular. Let’s explore event binding in Angular further.