Monday, October 22, 2018

Event Binding in Angular

Event binding is one-way binding in Angular from the view to the component class. 
Event binding is used to handle events which arise out of the controls in the view, like button click event, textbox blur event etc. 
Event binding in Angular is represented using a set of braces (). The event to be triggered is placed inside the braces like (click), and the handling function comes after the = sign, as follows. 
(click)="clickHandler()"

Let us understand event binding with a simple example, we have a button in the view whose click event is bound to the handler function clickHandler(), in the hander function we set the property clickMessage which will get displayed in the view as interpolation.

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() { }
  clickMessage ='';
  clickHandler() {
    this.clickMessage = 'You clicked the Button.';
  }
}
app.component.html
<div<
  <input type="button" (click)='clickHandler()' value="Click Me"<
  {{clickMessage}}
</div<

In the view we tie the buttons click event with the event handler function clickHandler. In the event handler function we set the clickMessage property, and this gets displayed in the view as an interpolation. The output is as follows. 





Search Flipkart Products:
Flipkart.com

No comments: