Create your account

Already have an account? Login here

Create account

Angular 2 Property & Event Binding Tutorial

By Gary simon - Nov 02, 2016

Angular 2 binding allows us to provide a means for communication between our views (HTML) and components. There are different types of bindings that handle certain tasks. In this tutorial, we'll focus on two of them; property binding and event binding.

First, if you prefer watching a video tutorial, view here:

Angular 2 Property Binding

Let's say for example we have an image (img element in HTML) that's dynamic, based on some type of logic defined in our component class. We would use property binding to handle that image. Here's how:

 

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `

<h1>My First Angular App</h1>

<img [src]="imageUrl">
<img bind-src="imageUrl">

})

export class AppComponent { 

imageUrl = 'https://angular.io/resources/images/logos/angular2/angular.png';

}

Notice the two img elements in the template property. Both achieve the same result.

Property binding can be defined either by wrapping the attribute in [brackets] or by prefixing bind- with the attribute name. Property binding allows us to send logic from the component class, to the view.

Note: You can use interpolation as well: <img src="{{imageUrl}}">

 

Angular 2 Event Binding

Event binding allows us to work in reverse from property binding. We can send information from the view, to the component class. Such information usually involves a click, hover or typing. Below is an example of event binding:

//...
template: `

<h1>My First Angular App</h1>

<img [src]="imageUrl" (click)='myMethod()'>
<img [src]="imageUrl" on-click='myMethod()'>

`

//...
imageUrl = 'https://angular.io/resources/images/logos/angular2/angular.png';

myMethod() {
   console.log('Hey!');
}

//...

Notice the 2 img elements. Once again, both achieve the same result.  Event binding can be defined either by wrapping the event in (paranthesis), or by prefixing it with on-. In the scenario above, if a person clicks on the image, the console will log "Hey!".

You can also pass along information about the event to the component class:

//...
template: `
<img [src]="imageUrl" (click)='myMethod($event)'>
`

//...
myMethod(event:any) {
   console.log(event);
}
//...

The event object will contain a lot of information that can be used in the logic defining the method.


Share this post

Chat with us




Say something about this awesome post!