Angular 2 : Data Bindings

Angular provides many kinds of data binding

We can group all bindings into three categories by the direction in which data flows. Each category has its distinctive syntax:

Interpolation

Any property in Component class can be shown as text through Interpolation written as {{}}

Property Binding

It is similar to Interpolation but it is a preferable way of doing one way binding, especially in case of styles and attribute bindings. It has a syntax []

Event Binding

It binds and event to a Component function. The events are standard browser events such as Click, DoubleClick etc.

Two-way binding

It binds a Component property to an input element. The changes gets reflected in the property at the same time. This is actually a combination of One-way binding and Event-binding. It is written as Banana-in-a-box syntax [(..)]. The outer braces shows One-way binding and the inner brace shows Event binding.


To Visualize

DOM


Interpolation : {{someText}}
Property Binding :
<img [src]='prop.URL'>
Event Binding :
<button (click)='showImage()'>
Two way Binding :
<input [(ngModel)]='Name'>

Component


Example

<input type="text" [value]="myName">
<button (click)="colorChange(textColor)" [style.color]="textColor">Change My Color</button>
<input type="text" [(ngModel)]="textColor">

<table border=2>
    <!--  expression calculates colspan=2 -->
    <tr>
        <td [attr.colspan]="1 + 1 + 1">Left - Center - Right</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
    </tr>
</table>

Live Code 

Plunker here: https://embed.plnkr.co/plunk/BT8gj5?show=app,preview

No comments :

Post a Comment

Comment Here