Showing posts with label Event Binding. Show all posts
Showing posts with label Event Binding. Show all posts

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. 




Friday, October 19, 2018

Types of Binding in Angular

Binding is used to bind the model properties and controller functions to the View. Let us now see the different types of bindings offered by Angular.

Angular provides 4 different types of binding.

1. Interpolations
2. Property Binding
3. Event Binding
4. Two way binding

What is Biding in Angular?

Binding is the concept by which the properties and functions in the model/controller are bound to the View. Remember that Angular is a client side MVC architecture.

In AngularJS the $scope was the model which contains the model properties and the controller had the function. Views are HTML files or other files like the MVC view files (.cshtml). Both the model properties and the controller functions are bound to the view using Binding.

In Angular the Component class contains the model properties and functions and the template .html files represent the View. The model properties and functions are bound to the view template file using Binding.