Angular 2.0 Binding syntax

In angular 2.0 binding syntax has changed a bit. Data binding between component and DOM can be achieved in following manner as shown below, each of these data binding types have specific syntax.

Angular2DataBinding

  • Interpolation – It is one way in from component to DOM. It evaluates expression between 2 curly braces
    <h3>Vehicle Name: {{vehicle.name}}</h3>
    

    They are not editable and the value does not go back to the component. Very useful for read only expressions. What @ property binding to DOM attributes, in older angular we attributes prefixed with ng-* like ng-src etc, this changes in Angular 2.0, it looks some thing like this

    <img [src]="vehicle.imageUrl"/>
    

    You can take any HTML5 property and bind to it. You can bind to custom properties in directives as well. In summary you can bind to element, component or directive property.

  • Event binding – This is reverse flow from DOM to component. Inward data flow from component was denoted with open close square brackets, reverse flow through event bindings from DOM to component is round brackets like show below
    <button (click)="Save()">Save</button>
    

    It executes an expression when and event occurs.

  • Two way data binding – It is value in and value out. For two way binding we have a special directive called ngModel
    <input type="text" [(ng-model)]="vehicle.name"/>
    

    We want to allow value to come in that’s reason we have square bracket and we want passback the updated value to component that’s reason we circular brackets.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s