-
Notifications
You must be signed in to change notification settings - Fork 1
Data Binding
Data Binding
Event Binding
Two-way Binding
-
Data Binding is the process of communication between your Component and the View. It is the process of transfer of data from Component to View.
-
Following are different types of Data Binding:
-
- String Interpolation uses template expressions in double curly
{{ }}
braces to display data from the component, the special syntax{{ }}
, also known as moustache syntax. The{{ }}
contains JavaScript expression which can be run by Angular and the output will be inserted into the HTML - Syntax
{{ type_script_expression }}
. - Here
type_script_expression
must be an expression that always evaluates to String.
Correct way Incorrect Way .ts
filename: string = 'Hello World'
.html
file<p>Output: {{ name }} </p>
.ts
fileflag: boolean = false
.html
file<p>Output: {{ flag }} </p>
- You can also use a method call, but that should always return a string
- You cannot use any conditional statement or loop statements. You're allowed to use ternary expression though.
Correct way Incorrect Way .ts
filename: string = 'Hello World'
getName() { return this.name; }
id: number = ['online', 'offline']; /* number can easily be converted to string in runtime */
.html
file<p>{{ 'Name' }} is <strong>{{ getName() }}</strong></p>
<p>Status: {{ (id%2 == 0) ? "online" : (id%2 == 1) ? "offline" : "" }}</p>
.ts
filename: string = 'Hello World'
getName() { return this.name; }
id: number = ['online', 'offline']; /* number can easily be converted to string in runtime */
.html
file<p>{{ 'Name' }} is <strong>{{ while(someCondition) { getName() } }}</strong></p>
<p>Status: {{ if(someCondition) { ... } else{ ... } }}</p>
- String Interpolation uses template expressions in double curly
-
-
Bind DOM property with value from TypeScript i.e. by wrapping brackets around an element property and binding it to a component property.
-
To set an element property to a non-string data value, you must use property binding. E.g.
.ts
fileimageURL: string = 'https://www.google.com/someImage.png'; width: number = 230; height: number = 230;
.html
file<img [src]="imageURL" [width]="width" [height]="height" />
-
-
- Adding
bind-
before the element property also achieves the same thing as property binding. E.g.
- Adding
<img bind-src="imageURL" bind-width="width" bind-height="height" />
-
- Set the value of an attribute directly with an attribute binding.
- Usually, setting an element property with a property binding is preferable to setting the attribute with a string. However, sometimes there is no element property to bind, so attribute binding is the solution.
- Consider the
ARIA
andSVG
. They are purely attributes, don't correspond to element properties, and don't set element properties. In these cases, there are no property targets to bind to. - Attribute binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix
attr
, followed by a dot.
, and the name of the attribute. You then set the attribute value, using an expression that resolves to a string, or remove the attribute when the expression resolves tonull
.
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>
-
- Add and remove CSS class names from an element's class attribute with a class binding.
- Class binding syntax resembles property binding, but instead of an element property between brackets, start with the prefix
class
, optionally followed by a dot.
and the name of a CSS class:[class.class-name]
.
<div [attr.class]="resetClasses">Reset all classes at once</div> <div [class.item-clearance]="itemClearance">Add another class</div> <div bind-class.special="isSpecial">This class binding is special too.</div>
-
- You can set inline styles with a style binding.
- Style binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix
style
, followed by a dot.
and the name of a CSS style property:[style.style-property]
. - This technique is suitable for setting a single style, but consider the
NgStyle
directive when setting several inline styles at the same time.
<button [style.color]="isSpecial ? 'red': 'green'">Red</button> <button [style.background-color]="canSave ? 'cyan': 'grey'" >Save</button>
- Some style binding styles have a unit extension. The following example conditionally sets the font size in
em
and%
units
<button [style.font-size.em]="isSpecial ? 3 : 1" >Big</button> <button [style.font-size.%]="!isSpecial ? 150 : 50" >Small</button>
- Angular automatically escapes data if you use
ng-bind
or the{{ curly brace syntax }}
when it encounters HTML, it will display them as string literals rather than interpreting them as HTML. - Say for example when we have data like
<em>Hello World</em>
, it will be rendered as a string<em>Hello World</em>
and not as Hello World - This helps to protect us from malicious attacks such as XSS by sanitizing any data that may contain script tags
-
Data Type
- Angular evaluates all expressions in double curly braces, converts the expression results to strings, and concatenates them with neighboring literal strings. Finally, it assigns this composite interpolated result to an element or directive/component property.
- Property binding does not convert the expression result to a string. *So if you need to bind something other than a string to your directive/component property, you must use property binding.
-
Example
- We are disabling a button by binding to the Boolean property
isDisabled
.<button [disabled]='isDisabled'>Try Me</button>
- Interpolation instead of property binding, the button will always be disabled irrespective of
isDisabled
class property value is true of false. Because final value assigned would always be a string instead of a required boolean value.<button disabled='{{isDisabled}}'>Try Me</button>
- We are disabling a button by binding to the Boolean property
-
Event Binding is the process of communication between your View and the Component. It is the process of triggering of event from View to Component in order to perform a specific action.
-
The target inside the
()
is an event we want to listen for, we are listening for the click event. The text to the right of=
is some javascript which will be called every time a click event occurs.
<button class="btn btn-secondary" (click)="onClickChangeAlignment()">Changing text</button><br>
{{align}}
align: string = 'left';
onClickChangeAlignment() {
const align: string[] = ['top', 'middle', 'bottom', 'left', 'right'];
const index: number = Math.floor(Math.random() * 4);
return this.align = align[index];
}
-
The
(click)
to the left of the equals sign identifies the button's click event as the target of the binding. The text in quotes to the right of the equals sign is the template statement, which responds to the click event by calling the component's onClickChangeAlignment method. -
Note that you remove
on
fromonclick
,onkeypress
etc -
Miscellaneous: Event Bubble
-
DOM events carry a payload of information that may be useful to the component.
-
When a user inputs the data, the input event occurs, and Angular provides a corresponding DOM event object in the
$event
variable which this code passes as a parameter to the component's printData() method.
<input type="text" class="form-control" (input)="printData($event)" /><br>
someString: string = '';
printData(event: Event) {
return this.someString = (event.target as HTMLInputElement).value;
}
-
All standard DOM event objects have a target property, a reference to the element that raised the event. In this case, target refers to the
<input>
element andevent.target.value
returns the current contents of that element. -
Not all elements have a value property so it casts target to an input element. Here typescript doesn't allows to use
value
onevent.target
and therefore we need to cast it withHTMLInputElement
-
Two Way Data Binding is the process of to-and-fro communication between your View and the Component. It combines the input and output binding into a single notation using the
ngModel
directive. -
You need to enable the
ngModel
directive. This is done by adding theFormsModule
to theimports[]
array in theAppModule
. You then also need to add the import from@angular/forms
in theapp.module.ts
file:import { FormsModule } from '@angular/forms';
<label>Enter username:</label>
<input type="text" class="form-control" [(ngModel)]="username" /> <br>
<p>username entered is: {{username}}</p>
/* app.module.ts */
import { FormsModule } from '@angular/forms';
imports: [ FormsModule ]
/* component.ts */
username: string = '';
-
Creating Custom Two-Way Data Bindings