Binding In Angular-All In One By Sagar Jaybhay

All About Binding In Angular By Sagar Jaybhay

Data Binding In Angular Application

Interpolation

{{ }} this syntax is used for interpolation. It works well when you need to update the content dynamically like heading, titles or messages in div, a span where you want to insert text.

Property Binding

This works well for adding images or properties where you need one-way binding which full fill your requirement. Means it will flow from component to dom.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
`
})
export class databinding
{
    title='Best Image Of 2019'
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg'

}

This code is for property binding and interpolation.

Interpolation and Property Binding In ANgular

Attribute Binding

In HTML is like a tree of dom elements like from start HTML after that head and so on. There are so many HTML elements has one to one mapping for dom element. There is some exception for that but most of it has. Ex colspan of the table did not have the corresponding property of the dom element.

Dom Element to Html Element

So the corresponding dom property is not present so for binding you required to put attr before property name like shown below.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';

}
Property Attribute and Interpolation

Class Binding

Suppose you want to add some class based on some condition. To bind CSS class to element we can use class binding as shown below.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger">Submit</button>

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;

}
class binding

Below is the class binding result.

class binding result

Style Binding

It is some variation of property binding which is like to class binding. Based on some condition we can bind the style or change some style of HTML dom element.

style binding
import { Component } from "@angular/core";

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;
}
style binding 7-code

Event Binding

This is used for binding the event like button click, drop-down box value changed and which is attached by using event binding. On button click we added code for alert and image show the result what we get below also code is added.

Event Binding
import { Component } from "@angular/core";

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>

<button class="btn btn-success" (click)="onClickMe()"  >Click Me</button>
`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;
    onClickMe(){
        alert('I am in click button event handler');
    }
}
Click event Binding

Event Bubbling

This is standard dom event propagation from inner element to outer element event bubbled up.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
<div (click)="onDivClicked()">
<button class="btn btn-success" (click)="onClickMe($event)"  >Click Me</button>
</div>
`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;

    onDivClicked(){
        alert('Div is clicked');
    }
    onClickMe($event){
        alert('I am in click button event handler');
        console.log($event);
    }
}

In this code, the first button event is called after that div event gets called to stop event bubbling you need to stop that.

$event

Is the object we pass from dom. This $event object carries a payload and useful information that might required to process or required. The information present like below which is for a button click.

1.	MouseEvent {isTrusted: true, screenX: -1833, screenY: 525, clientX: 87, clientY: 422, …}
1.	altKey: false
2.	bubbles: true
3.	button: 0
4.	buttons: 0
5.	cancelBubble: false
6.	cancelable: true
7.	clientX: 87
8.	clientY: 422
9.	composed: true
10.	ctrlKey: false
11.	currentTarget: null
12.	defaultPrevented: false
13.	detail: 1
14.	eventPhase: 0
15.	fromElement: null
16.	isTrusted: true
17.	layerX: 87
18.	layerY: 872
19.	metaKey: false
20.	movementX: 0
21.	movementY: 0
22.	offsetX: 66
23.	offsetY: 16
24.	pageX: 87
25.	pageY: 872
26.	path: (8) [button.btn.btn-success, div, myimage, app-root, body, html, document, Window]
27.	relatedTarget: null
28.	returnValue: true
29.	screenX: -1833
30.	screenY: 525
31.	shiftKey: false
32.	sourceCapabilities: InputDeviceCapabilities {firesTouchEvents: false}
33.	srcElement: button.btn.btn-success
34.	target: button.btn.btn-success
35.	timeStamp: 2728.2799999993586
36.	toElement: button.btn.btn-success
37.	type: "click"
38.	view: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
39.	which: 1
40.	x: 87
41.	y: 422
42.	__proto__: MouseEvent

This information might be changed from event to event. So to stop propagation we need to use below the line of code where you want to stop that event bubbling.

$event.stopPropagation();

Event Filtering

Suppose you want to call the method to enter key-press to that there are 2 methods in which first is shown below. In which by using $event object you get key-code and by comparison you add condition and based on that code execute.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
<div (click)="onDivClicked()">
<button class="btn btn-success" (click)="onClickMe($event)"  >Click Me</button>
</div>

<br/>
<br/>
<input (keyup)="onkeyUp($event)">

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;

    onDivClicked(){
        alert('Div is clicked');
    }
    onClickMe($event){

        $event.stopPropagation();
        alert('I am in click button event handler');
        console.log($event);
    }

    onkeyUp($event){
        if($event.keyCode===13)
        alert("eneter press  ==> "+ $event.target.value);

    }

The second way is the angular way.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
<div (click)="onDivClicked()">
<button class="btn btn-success" (click)="onClickMe($event)"  >Click Me</button>
</div>

<br/>
<br/>
<input (keyup.enter)="onkeyUp()">

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;

    onDivClicked(){
        alert('Div is clicked');
    }
    onClickMe($event){

        $event.stopPropagation();
        alert('I am in click button event handler');
        console.log($event);
    }

    onkeyUp(){       
        alert("eneter press  ==> ");

    }
}

In this no need to pass $event object to the function and no need to a comparison of key-code.

Template Variable

Now in this our previous example we take an input box and we pass this $event object and by using this object $event.target.the value we get value whatever put in text-box but there is another way simple and less cluttered to get the value of text-box by using template variable.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
<div (click)="onDivClicked()">
<button class="btn btn-success" (click)="onClickMe($event)"  >Click Me</button>
</div>

<br/>
<br/>
<input #email (keyup.enter)="onkeyUp(email.value)">

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;

    onDivClicked(){
        alert('Div is clicked');
    }
    onClickMe($event){

        $event.stopPropagation();
        alert('I am in click button event handler');
        console.log($event);
    }

    onkeyUp(emailid){       
        alert("eneter press  ==> "+emailid);

    }
}
Template Binding

Two-Way Binding

In the above example we saw template variable binding but is only one way. If we do object-oriented programming we need to use object behavior like object should encapsulate the things or properties so for that we create a variable in component and add refer this to value property in template Html. This is the banana in the box [()] for this you need to use ngModel property and this is present in FormsModule in angular/forms.

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

@Component({
selector:'myImage',
template:`
<h2>{{title}}</h2>
<br/>
<img [src]="imageUrl"/>
<table>
<tr>
<td [attr.colspan]="colspan"></td>
</tr>
</table>

<button class="btn btn-primary" [class.btn-danger]="isDanger"  >Submit</button>

<button class="btn btn-primary" [style.backgroundColor]="isActive? 'blue':'Yellow'" >Style Binding</button>
<div (click)="onDivClicked()">
<button class="btn btn-success" (click)="onClickMe($event)"  >Click Me</button>
</div>

<br/>
<br/>
<input [(ngModel)]=email (keyup.enter)="onkeyUp()">

`
})
export class databinding
{
    title='Best Image Of 2019';
    colspan=2;
    imageUrl='https://www.thestatesman.com/wp-content/uploads/2018/12/Happy-New-Year6.jpg';
    isDanger=true;
    isActive=true;
    email="abc@xyz.com";
    onDivClicked(){
        alert('Div is clicked');
    }
    onClickMe($event){

        $event.stopPropagation();
        alert('I am in click button event handler');
        console.log($event);
    }

    onkeyUp(){       
        alert("eneter press  ==> "+this.email);
    }
}

This FormsModule you need to include app.module.ts in the imports array.

FormsModule

If you don’t include this you will get an error like below.

compiler.js:2175 Uncaught Error: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. ("
<br/>
<br/>
<input [ERROR ->][(ngModel)]=email (keyup.enter)="onkeyUp()">

"): ng:///AppModule/databinding.html@20:7
    at syntaxError (compiler.js:2175)
    at TemplateParser.parse (compiler.js:11292)
    at JitCompiler._parseTemplate (compiler.js:25837)
    at JitCompiler._compileTemplate (compiler.js:25825)
    at compiler.js:25769
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:25769)
    at compiler.js:25682
    at Object.then (compiler.js:2166)
    at JitCompiler._compileModuleAndComponents (compiler.js:25681)

If this error we get.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *