In this post we are going to learn what is event binding in angular, event binding is most important thing without event binding we can not build an angular application.
What is event binding in angular ?
Event binding is a technique that allows us to bind JavaScript events to a HTML element . In event binding the data flow happens from view to component (one-way).
Syntax
<button (click)="function()">Click</button>
Example 1: (click event)
Create button and bind a click event to it , when the user clicks the button we will show alert popup with this message "You have clicked the button".
src/app/app.component.html
<button (click)="showMessage()">Click</button>
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public showMessage(){
alert("You have clicked the button");
}
}
Output
Example 2: (change event)
Create checkbox and bind a change event to it , when the user check the checkbox we will show alert popup with this message "You have checked the checkbox".
src/app/app.component.html
<label>Check Box</label>
<input type="checkbox" (change)="showMessage()">
src/app/app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public showMessage(){
alert("You have checked the checkbox");
}
}
Output
I hope this article is helpful for you , i am very glad to help you thanks for reading