KEMBAR78
AJS Notes - Unit-2 | PDF | Document Object Model | Angular Js
0% found this document useful (0 votes)
8 views12 pages

AJS Notes - Unit-2

Data binding in Angular is a technique that synchronizes data between the UI and the underlying data source, facilitating a seamless connection between the view and business logic. It can be categorized into one-way and two-way data binding, with various methods such as string interpolation, property binding, and event binding. Additionally, the Document Object Model (DOM) is crucial for manipulating HTML and XML documents, enabling dynamic content updates and user interactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views12 pages

AJS Notes - Unit-2

Data binding in Angular is a technique that synchronizes data between the UI and the underlying data source, facilitating a seamless connection between the view and business logic. It can be categorized into one-way and two-way data binding, with various methods such as string interpolation, property binding, and event binding. Additionally, the Document Object Model (DOM) is crucial for manipulating HTML and XML documents, enabling dynamic content updates and user interactions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Angular - UNIT-2

DATA BINDING
Unit-2

What is Data Binding?

Data binding is a very useful and powerful feature used in software development technologies.
It acts as a bridge between the view and business logic of the application.

Everything we do in component. Data binding is if we want to show content from typescript file
in html or html file in typescript is called data binding.

Data binding is a programming technique that automatically synchronizes data between a user
interface (UI) element and its underlying data source, meaning any change to the data is
reflected instantly in the UI, and vice versa, eliminating the need for manual updates to the UI
whenever data is modified; essentially, it establishes a live connection between the visual
representation of data and the actual data itself, simplifying application development by
separating the concerns of data management and UI presentation

Types of data binding.

1. One-Way Data Binding


The one-way data binding is an approach where a value is taken from the data model and
inserted into an HTML element. There is no way to update model from view. It is used in
classical template systems. These systems bind data in only one direction.
Model/.ts file --> DOM/HTML
(or)
DOM/HTML --> Model/.ts

In One-Way data binding: data can be passed in the below four ways:
 String Interpolation
 Attribute binding
 Class binding
 Style binding
 Event binding

2. Two-Way Data Binding


Data binding in Angular apps is the automatic synchronization of data between the model and
view components. Data binding lets you treat the model as the single-source-of-truth in your
application. The view is a projection of the model at all times. If the model is changed, the view
reflects the change and vice versa.
Model/.ts file --> DOM/HTML
Example-1 :
<!DOCTYPE html>
<html>
<body>
<div ng-app="" ng-init="firstName='Ravindra Babu'">
<p>Input something in the input box:</p>

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|1


Angular - UNIT-2

<p>Name: <input type="text" ng-model="firstName"></p>


<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>

In the above example, the {{ firstName }} expression is an AngularJS data binding expression.
Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

Example-2 : Let's take another example where two text fields are bound together with two ng-
model directives:

<!DOCTYPE html>
<html>
<body>
<div data-ng-app="" data-ng-init="quantity=1;price=20">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>

Document Object Model (DOM)

What is DOM used for?


The Document Object Model (DOM) is a programming API for HTML and XML documents. It
defines the logical structure of documents and the way a document is accessed and
manipulated.

Does Angular use real DOM?


Angular uses a real DOM, whereas React uses a virtual DOM. The entire tree structure is updated
when a change is performed in Angular.

What are DOM commands?


The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and
each node contains objects. DOM methods allow programmatic access to the tree. With them,
you can change the document's structure, style, or content. Nodes can also have event handlers
attached to them.

Why is DOM Required? Dynamic Content Updates: Without reloading the page, the DOM
allows content updates (e.g., form validation, AJAX responses). User Interaction: It makes your
webpage interactive (e.g., responding to button clicks, form submissions).

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|2


Angular - UNIT-2

Is DOM important to learn?


The DOM is the core of how a web page works. It's absolutely essential to understand it. In the
case of a frontend developer, pretty much everything you do on a daily basis consists of
performing actions on the DOM.

How DOM is working?


The Document Object Model (DOM) is a programming interface for web documents. It
represents the page so that programs can change the document structure, style, and content.
The DOM represents the document as nodes and objects; that way, programming languages can
interact with the page.

What are the 3 parts of DOM?


The DOM is separated into three parts: Core, HTML, and XML. The Core DOM provides a low-
level set of objects that can represent any structured document.

What is the Document Object Model?


Introduction. The Document Object Model (DOM) is an application programming interface
(API) for HTML and XML documents. It defines the logical structure of documents and the way
a document is accessed and manipulated.

Why do we use DOM?


The DOM (Document Object Model) is an interface that represents how your HTML and XML
documents are read by the browser. It allows a language (JavaScript) to manipulate, structure,
and style your website. It represents an Angular JS click event.
ng-disabled directive: The ng-disabled directive binds AngularJS application data to the
disabled attribute of HTML elements. In the below code, it binds a model to a checkbox.

1. One-way data binding:


Data flows in a single direction, either from the component to the view or from the view to the
component. It includes:
1. Interpolation: Displays data from the component in the view using double curly
braces {{ }}.
2. Property binding: Binds a component property to an HTML element's property using
square brackets [ ].
3. Attribute binding: Similar to property binding, but used for HTML attributes that are
not DOM properties.
4. Class binding: Adds or removes CSS classes based on a component expression.
5. Style binding: Sets inline styles based on a component expression.
6. Event binding: Allows the component to respond to events from the view, such as
button clicks, using parentheses ( ).

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|3


Angular - UNIT-2

1. Interpolation: Interpolation: In Angular, interpolation is a way to embed expressions


directly into HTML templates. It allows for dynamic data binding, where values from the
component class are displayed in the template. The syntax for interpolation uses double
curly braces {{ }}. Any expression placed within these braces will be evaluated and its result
will be rendered as text in the HTML.

For instance, if a component has a property named userName, its value can be displayed in
the template using {{ userName }}. Angular will automatically update the displayed value
whenever the userName property changes in the component.

Html:

<p>{{ sayHello() }}</p>

<p>{{ add(x,y) }}</p>

Ts:

sayHello() {
return "Hello from the component!";
}
add(x: number, y: number): number {
return x + y;
}
x=13; y=5;

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|4


Angular - UNIT-2

2. Property Binding
What is a property binding?
Property binding is one of the key features in Angular that allows developers to dynamically set
properties of HTML elements or directives.

What is Angular binding?


Angular data binding is a two-way process: it can both send and receive data. This means that
when you change something in your view, the model updates automatically, and vice versa. The
ngModel directive makes this two-way data binding possible.

What is event binding and property binding in Angular?


Angular provides several types of data binding: Interpolation: Uses {{}} syntax to render data.
Property Binding: Binds a property of a DOM element to a field in your component. Event
Binding: Allows the application to respond to user input in the form of events.

What is interpolation in Angular?


Angular interpolation is a way to bind data from your component to the HTML template. It
allows you to embed expressions within double curly braces ( {{ }} ) in the template, and
Angular will replace those expressions with the actual values from your component.

What is the difference between property binding and interpolation?


Interpolation is used to just display a piece of data in HTML, such as displaying a title or a name.
Property binding lets us bind a property of a DOM object, for example the hidden property, to
some data value.
What is ngModel in Angular?
NgModel is a directive in Angular that enables two-way data binding between a form control
and a component class. It's used to synchronize data in forms, such as when a user enters data
into an input field.
How it works
 NgModel creates a FormControl instance from a domain model
 It binds the FormControl instance to a form control element, such as an input, select, or
textarea
 It uses property binding to pass data from the component class to the element
 It uses event binding to pass data from the UI to the component class after a user action
What it does
 Provides validation behavior, such as required, email, number, and URL
 Keeps track of the state of the control, such as valid, dirty, touched, and error
 Sets CSS classes on the element, such as ng-valid, ng-dirty, ng-touched, and ng-empty
 Registers the control with its parent form
How to use it
 Import the FormsModule into your Angular module
 Use the syntax [(ngModel)] to indicate two-way binding

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|5


Angular - UNIT-2

What are the disadvantages of interpolation in Angular?

Limitations of Interpolation
While interpolation is a powerful and convenient tool, it does have some limitations: One-Way
Binding: Interpolation only supports one-way data binding, meaning it can only display data
from the component to the view. For two-way data binding, Angular provides the ngModel
directive.

Example -1:
Button Enable and Disable:
Enter the following in .html:
Name: <input type="text">
<button [disabled]=isdisabled>Submit</button>

Enter the following in .ts:


export class Appcomponent {
isdisabled:boolean=true;
}

[disabled] is property binding 'isdisabled' is the property and we cannot use string
interpolation {{}}, string interpolation returns string but we need boolean value true or false.
so we need to bind with square brackets.

Example -2:
Img src is interpolation
To insert images
Step-1: insert image into public directory
Step-2: export class AppComponent {
title = "Title Content";
path:string = "1.jpg";
}
Step-3:
<html>
<h1>Ravindra's Page</h1>
<p> {{title}} </p>
<img src = {{path}} alt = "No-Picture" >
or
<img [src] = imgpath alt = "No-Picture" >
</html>

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|6


Angular - UNIT-2

3. Class Binding: Class binding in Angular enables the dynamic addition and removal of CSS
classes to HTML elements. This functionality is achieved through binding expressions that,
based on their truthiness or falsiness, determine whether a specific class is applied or
removed from the element's class attribute. Angular offers several ways to implement class
binding:

Single class binding: It conditionally adds or removes a single CSS class. The syntax
involves using square brackets around the class prefix, followed by a dot and the class name,
and assigning it a boolean expression.
<div [class.active]="isActive"></div>

In this example, the class active is added to the div element only when
the isActive expression evaluates to true.

Multiple class bindings: It allows for conditionally applying multiple classes using an
object where keys are class names and values are boolean expressions.
<div [class]="{ 'active': isActive, 'disabled': isDisabled }"></div>

Binding to the class property: It directly manipulates the entire class attribute by
assigning it a string, array, or object.

<div [class]="classExpression"></div>
The classExpression can be a string of class names separated by spaces, an array of class names,
or an object as described in multiple class bindings.
Class binding in Angular simplifies the process of dynamically updating the appearance of
elements based on component logic, enhancing the interactivity and responsiveness of
applications.
What is the use of class binding in Angular?
Class binding is used to set a class property of a view element. We can add and remove the CSS
class names from an element's class attribute with class binding. The class binding syntax is
also like property binding. In property binding, we only specify the element between brackets.
Example -1: (Single class binding)
html:
<h2 [class]="isinaction? 'inaction' : 'noaction' " > LEIT</h2>

Based on class ternary operator condition, the action is taken.

css:
.inaction {
background-color : green;
color : white;
}

.noaction {
background-color : grey;

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|7


Angular - UNIT-2

color : white;
}

ts:
export class AppComponent {
isinaction : boolean=true;
}

isinaction, inaction and noaction are variables/properties

1. Multiple class Binding with multiple conditions:

html:
<h3 [class]="{cond1:true}" > LENDI</h3>

Instead of true i can give a variable and in typescript i can give true of false.

css:
.cond1{
border:5px solid blue;
}

Example -2: (Multiple class binding with multiple conditions)

html:
<h3 [class]="{cond1: var1}" > LENDI</h3>

css:
.cond1{
border:5px solid blue;
}

ts:
var1:boolean = true;

Example -3: (Multiple class binding with multiple conditions)

html:
<h3 [class]="{cond1: var1, isinaction:inaction }" > LENDI</h3>
.
css:

.inaction {
background-color : green;
color : white;
}

.noaction {

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|8


Angular - UNIT-2

background-color : grey;
color : white;
}

.cond1{
border:5px solid blue;
}

ts:
isinaction : boolean=true;

var1:boolean = true;

3. Another way of html file for the Multiple class Binding with multiple conditions:

html:
<h3 [class]="['cond1', 'inaction' ]" > LENDI</h3>

3. Another way of html file for the Multiple class Binding with multiple conditions:

html:
<h3 [class.inaction]= isinaction> LENDI</h3>

What does async mean in Angular? What Is Asynchronous Code in Angular?

When we talk about asynchronous code, we simply mean that the code isn't executed
sequentially and the process involves multithreading.

It is a form of parallel programming that executes a separate block of code without breaking
the primary application thread.

What is the purpose of using async?

The async keyword is what lets the JavaScript engine know that you are declaring an
asynchronous function. This is required to use await inside any function. When a function is
declared with async, it automatically returns a promise; returning in an async function is the
same as resolving a promise.

What is sync and async in Angular?

Async is non-blocking, which means it will send multiple requests to a server.

Sync is blocking — it will only send the server one request at a time and wait for that request
to be answered by the server.

Async increases throughput because multiple operations can run at the same time.

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|9


Angular - UNIT-2

Interpolation using pipes for data binding.

ts:

data = {

name : 'Ravindra Babu',

design : 'Asst. Prof.'

};

The above data is object type of data.

it shows object object. so we used pipe and json.

html:

<h1>{{data}}</h1>  <h1>{{data | json}}</h1>

Looping with ngFor

ts:

name=["Ramesh", "Kishore", "Ravi", "Laya"];

html:

<h1>{{name}}</h1>

It will print as a String. But we need to print as a list runnin a loop. so, instead of above html we
use below html.

html:

<h1>Name List</h1>

<ul>

<li *ngFor="let item of name">

{{item}}

</li>

</ul>

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|10


Angular - UNIT-2

Looping with ngFor

ts:
items = [
{
name: 'Pizza',
price: 10
},
{
name: 'Burger',
price: 5
},
{
name: 'Fries',
price: 2
}
html:
<h4>Menu</h4>
<ul>
<li *ngFor="let item of items">
<a > {{ item.name }} </a>
<a> {{ item.price }} </a>
</li>
</ul>

Condition with ngif

ngIf (Structural directive)

we can add / remove DOM elements based on some condition

-ngIf

-ngIf with else statement

-ngIf with then and else statement

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|11


Angular - UNIT-2

html:
<h5 *ngIf="1">This is Vision R</h5>
--if *ngIf="0" - it will not display above data.
ngIf - else
html:
<p *ngIf="age>17;else elseBlock">Eligible to Vote</p>
<ng-template #elseBlock>
<p> You are not Eligible to vote</p>
</ng-template>
ts:
age=20;

@Input & @Output decorator


@Input - Parent to child Data Transfer
@Output - child to parent Data Transfer
To create another component below command is used
c:\users\baha>ng g c sample
app.component.html
<app-sample></app-sample>
-now run
From Parent component to Child Component - Sending Data
child component (sample.ts)
@Input() Inputdata:any;
ngOnInit(): void {
console.log('Child data', this.Inputdata)
}
app.component.ts
title = 'This is parent component data ECE C Class';
app.component.html
<app-sample [Inputdata]="title"></app-sample>
}

R S Ravindra Babu, Asst. Prof., Dept. of CSE, LIET. Page|12

You might also like