09.Data Binding.
Data Binding.
Data binding ආකාර 2 කි.
- One-way Data Binding - component to view (DOM) or view to the component
- Two-way Data Binding - component to view and view to the component.

One-way Data Binding in Angular
Component to view (DOM) or view to component
One-way data binding will bind the data from the component to the view (DOM) or from view to the component. One-way data binding is unidirectional. You can only bind the data from component to the view or from view to the component.
a). From Component to View
01. Interpolation Binding
02. Property Binding
03. Attribute Binding
04. Class Binding
05. Style Binding
b). From View to Component
01. Event binding
From Component to View
Style and Class Binding
Directives – Directives are nothing but custom html element that angular provide.
Class Binding is really useful because it allows us to dynamically add or remove to HTML elements based on user interaction and state.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `<p style="color:red;text-align:center">THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- class binding --------</p>
<p [class]="!isAddClz?clzOne:clzTwo">class one binding 1</p>
<p [class.one]="isAddClz" >class one binding 3</p>
<p [ngClass]="classes" >multiple classes one binding </p>
<p>-------- style binding --------</p>
<p [style.color]="isAddStyle?'green':'orange'" [style.font-style] = "italicStyle" >style binding</p>
`,
styles: [`
.one{color:red;},
.two{color:blue;},
.three{font-style:italic;}
`]
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public isAddClz :boolean = true;
public clzOne :string = "one";
public clzTwo :string = "two";
public clzThree :string = "three";
public oneFromClz1 :string = "red";
public oneFromClz2 :string = "blue";
public isAddStyle :boolean = true;
public classes={
"one":!this.isAddStyle,
"two":this.isAddStyle
}
public styles={
color:"red",
fontStyle:"italic"
}
public italicStyle :string = "italic";
}
String Interpolation
Interpolation යනු, string data bind කිරීමටයොදාගන්නා technique එකක්වන අතර මෙය one-way data-binding technique එකකි.එනම් typescript code සිට HTML code එකට data bind කිරීමයි (component to view). මෙහිදී Data display (component to view) කිරීමට double curly braces {{ }} බාවිතාකරනුලබයි.
<input type="text" id="{{id}}" value="Type" disabled="{{!isDisable}}"/>
public id :string = "inputFieldId";
public isDisable :boolean = true;
String Interpolation බාවිතයෙන් string data පමනක් bind කලහැක.නමුත් Boolean හෝ string නොවන values bind කිරීමසදහා property binding බාවිතා කල හැක (property binding හරහා string values වුවද bind කලහැක).
Property Binding
Property binding is a technique, which will help to bind values to the properties (DOM properties) of HTML elements. Data binding can be done using {{}} or [] or 'bind-prefix'.
[id]="fieldId" bind-disabled="isDisable"
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `<p style="color:red;text-align:center">THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- property binding --------</p>
<br><br>
<input type="text" [disabled]="!isDisable" [id]="id" value="inputF2"/>
<br><br>
<input type="text" bind-disabled="isDisable" [id]="id" value="inputF3"/>
`,
styles: []
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public componentName :string = "BIND DATA";
public id :string = "inputFieldId";
public isDisable :boolean = true;
}
Let’s explore another example of setting the property of an Angular directive. In this case, we are setting the Angular directive ngClass property to a component's myClass property. Based on different conditions, it can add or remove a class
<div [ngClass]="myClass">Binding ngClass to the myClass property</div>
Why Use Property Binding?
The following are couple of the most useful reasons why we should use property binding.
01.Property binding helps you to bind the values to the target property of the element property enclosed within the square brackets.
Let's consider an example where we are binding the value "Hello World!" to the span element's innerHTML property. In this case, the target property is innerHTML.
<span [innerHTML]='Hello World!'></span>
We can also use the alternative canonical form 'bind-prefix' to bind the property.
<span bind-innerHTML='Hello World!'></span>
02.When we are binding an element property to a non-string data value, we use property binding. So that there will not be any change in the type of object we are binding to the view and the value that we have passed from the component. For easy readability, we can use the interpolation technique.
What to Avoid During Property Binding
The following are some of the things to avoid while using property binding.
01.When we are binding a method or function to property binding, that method may change a value in the component. Angular may or may not display the changed value. It may detect the change, but will throw a warning error.
02.When using property binding, make sure that your displayed values match.
03.The value within the template expression should evaluate to the type of value expected by the target property. Let's say the target property expects a number, then the number should be returned. If the target property expects a string, then string should be returned. If the target property expects an object, then the object should be returned.
Let's consider an example. Here the person property of the app-example expects an object of type person needs to be bound to it.
File Name: person.ts
export class Person{
name:string;
address:string;
}
File Name: app.component.ts
import{Component}from"@angular/core";
import{Person}from'../person';
@Component({
selector:'app-root',
template:`
<div>
<app-example [person]="personName"></app-example>
</div> `
})
exportclassAppComponent{
personName:Person;
}
04.Don't forget to put brackets around the property during property binding. Brackets will tell Angular to evaluate the template expression. If you forget to use brackets, then Angular will treat the string as a constant and initialize the target property with that string. It will not evaluate the string.
Let's consider an example:
If we don't use brackets during property binding, then we will get an error "person expects a Person object, not the string personName".
<app-example person="personName"></app-example>
You can omit the brackets when all of the following conditions meet:
The target property accepts a string value.
The string is a fixed value.
The initial value never changes.
Let's consider an example, where we are initializing the value property of the Example Component to a string "Hello World!", not a template expression. Angular sets this fixed string value only once and forgets about it.
<app-example value="Hello World!"></app-example>
05.Whenever we are binding element property to a non-string value, then we must use property binding. Otherwise, Angular will not be able to identify the type of data value that we are trying to bind to the DOM.
06.Angular will not allow the script tags to be placed in the HTML. It may lead to the leaks into the HTML and can cause a security issue. Both property binding and interpolation are not allowed within the HTML.
Let's consider an example, where we are a binding value from component to the view containing the script tag as shown below.
File Name: example.component.ts
import{Component}from"@angular/core";
@Component({
selector:'app-example',
template:`
<div>
<span [innerHTML]="scriptText"></span>
</div>
`
})
exportclassExampleComponent{
scriptText ='Template <script>alert("Text with script tag!")</script>Syntax';
}
Angular will sanitize the values before rendering them to the view. In the above case, Angular will throw a warning "sanitizing HTML stripped some content".
From Component to View
Event binding.
<input #MyInput type="text">
<button (click)="ClickOnBtn (MyInput.value)">Submit</button>
...
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `
<p>THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- Template Reference Variables --------</p>
<button (click)="eventDesc='this is eventDesc'">buttonOne</button>
{{eventDesc}}
<br><br>
<input #MyInput type="text">
<button (click)="ClickOnBtn (MyInput.value,$event)">buttonTwo</button>
{{inputVal}}
`,
styles: []
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public inputVal = "";
public ClickOnBtn (myInput,event){
console.log(event);
this.inputVal = myInput;
}
}
Click On ButtonTwo
Some time we want the information about the event itself. For this purpose we can use $event, this is a special character in angler.
Template Reference Variables
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `
<p>-------- Template Reference Variables --------</p>
<input #MyInput type="text">
<button (click)="ClickOnBtn (MyInput.value)">button</button><br/>
{{inputVal}}
`,
styles: []
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {}
public inputVal = "";
public ClickOnBtn (myInput){
console.log(event);
this.inputVal = myInput;
}
}
Angular will sanitize the values before rendering them to the view. In the above case, Angular will throw a warning "sanitizing HTML stripped some content".
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `
<p>THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- Template Reference Variables --------</p>
<button (click)="eventDesc='this is eventDesc'">buttonOne</button>
{{eventDesc}}
<br><br>
<input #MyInput type="text">
<button (click)="ClickOnBtn (MyInput.value,$event)">buttonTwo</button>
{{inputVal}}
`,
styles: []
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public inputVal = "";
public ClickOnBtn (myInput,event){
console.log(event);
this.inputVal = myInput;
}
}
Two-way Data Binding in Angular
<input [(ngModel)]="inputValForTwoWayBind" type="text">
Component to view and view to the component
මෙහෙදී “Hello World “ලෙස value එකක් inputValForTwoWayBind ටලබාදුන්නේනම්එය input field එකේ display වේ.
public inputValForTwoWayBind = ""Hello World";
එනම්මෙමඅවස්ථාවෙදී class එකේසිට template (HTML එකට ) data assignවේ .
තවද input field එකේ type කරනවිටඑම text එක class එකේ inputValForTwoWayBind variable එකට assign වේ.එනම් view එකේසිට class එකට data assignවේ.
Two-way data binding in Angular will help users to exchange data from the component to view and from view to the component. It will help users to establish communication bi-directionally.
Two-way data binding can be achieved using a ngModel directive in Angular. The below syntax shows the data binding using (ngModel), which is basically the combination of both the square brackets of property binding and parentheses of the event binding.
Before using ngModel to achieve two-way data binding, it’s very important to import the FormsModule from @angular/forms in app.module.ts file as shown below. FormsModule will contain the ngModule directive.
import { FormsModule } from '@angular/forms';
imports: [
FormsModule
]
If you do not import the FormsModule, then you will get Template parse errors and it will result in this error.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `<p style="color:red;text-align:center">THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- Two Way Binding --------</p>
<input [(ngModel)]="inputValForTwoWayBind" type="text"><br/>
{{inputValForTwoWayBind}}
`,
styles: []
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public inputValForTwoWayBind = "";
}
Full code for data binding
(Both one-way and two-way data binding)
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-databind',
template: `<p style="color:red;text-align:center">THIS IS {{componentName}} COMOPONENT<p><hr>
<p>-------- Interpolation --------</p>
<input type="text" id="{{id}}" value="Type" disabled="{{!isDisable}}"/>
<br>
<p>-------- property binding --------</p>
<br><br>
<input type="text" [disabled]="!isDisable" [id]="id" value="inputF2"/>
<br><br>
<input type="text" bind-disabled="isDisable"[id]="id" value="inputF3"/>
<p>-------- class binding --------</p>
<p [class]="!isAddClz?clzOne:clzTwo">class one binding 1</p>
<p [class.one]="isAddClz" >class one binding 3</p>
<p [ngClass]="classes" >multiple classes one binding </p>
<p>-------- style binding --------</p>
<p [style.color]="isAddStyle?'green':'orange'" [style.font-style] = "italicStyle" >style binding</p>
<p>-------- event binding --------</p>
<button (click)="eventDesc='this is eventDesc'">buttonOne</button>
<button (click)="ClickOnButton($event)">buttonTwo</button><br/>
{{eventDesc}}
<p>-------- Template Reference Variables --------</p>
<input #MyInput type="text">
<button (click)="ClickOnBtn (MyInput.value)">button</button><br/>
{{inputVal}}
<p>-------- Two Way Binding --------</p>
<input [(ngModel)]="inputValForTwoWayBind" type="text"><br/>
{{inputValForTwoWayBind}}
`,
styles: [`
.one{color:red;},
.two{color:blue;},
.three{font-style:italic;}
`]
})
export class DatabindComponent implements OnInit {
constructor() { }
ngOnInit() {
}
public componentName :string = "BIND DATA";
public id :string = "inputFieldId";
public isDisable :boolean = true;
public isAddClz :boolean = true;
public clzOne :string = "one";
public clzTwo :string = "two";
public clzThree :string = "three";
public oneFromClz1 :string = "red";
public oneFromClz2 :string = "blue";
public isAddStyle :boolean = true;
public classes={
"one":!this.isAddStyle,
"two":this.isAddStyle
}
public styles={
color:"red",
fontStyle:"italic"
}
public italicStyle :string = "italic";
public eventDesc = "";
public ClickOnButton(event){
console.log(event);
this.eventDesc = event.type;
}
public inputVal = "";
public ClickOnBtn (myInput){
console.log(event);
this.inputVal = myInput;
}
public inputValForTwoWayBind = "";
}
Comments
Post a Comment