What is Data Binding in Angular?
Data binding is a powerful feature in Angular, which allows us to communicate between the component and its view. Data Binding can be either one-way data binding [Angular Interpolation / String Interpolation, Property Binding, Event Binding] or two-way data binding.
In one-way data binding, the value of the Model is inserted into an HTML (DOM) element and there is no way to update the Model from the View. In two-way binding automatic synchronization of data happens between the Model and the View (whenever the Model changes it will be reflected in the View and vice-versa)
Angular supports four types of Data binding
- Interpolation / String Interpolation (one-way data binding)
- Property Binding (one-way data binding)
- Event Binding (one-way data binding)
- Two-Way Binding
In this Angular Data Binding article we will learn about Angular Interpolation / String interpolation (one-way data binding)
Angular Interpolation / String Interpolation
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.
Say if we put {{ 5 + 5 }} in the template 10 will be inserted into the HTML
Let’s take our HelloWorld application and understand String Interpolation
Template Expressions – helloworld.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
template: `
<h3>{{welcomeMessage}}</h3>
`,
styles: [`
h3 {
font-size:28px;
}`]
})
export class HelloWorldComponent implements OnInit {
welcomeMessage = 'Welcome to Angular Data Binding Example!!';
constructor() { }
ngOnInit() {
}
}
In the above code, we have created our HelloWorldComponent and initialized a string “welcomeMessage”, We are binding the “welcomeMessage” string to the DOM using String Interpolation in the template meta-data.
When the HelloWorldComponent is rendered on a page with the above template, it prints the value of “welcomeMessage” on the view. Below goes the output
app.component.html
<app-hello></app-hello>
Output:
Traverse into the HelloWorld app at the command prompt (C:\Angular5\HelloWorld) and run the command ng serve, this command will start the server and will launch the default Angular Application build by Angular CLI
Hit on the URL : http://localhost:4200/
Accessing the Template Reference Variables
Template Expression can access the Template Reference Variables too, You declare a Template Reference Variable by using the hash symbol (#).
In the below code #newWelcomeMessage defines the newWelcomeMessage reference variable in the <input> tag.
<input type="text" #newWelcomeMessage>
Let’s change our HelloWorldComponent to access the reference variable rather than hard-coded one.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-hello',
template: `
<h3>{{welcomeMessage}}</h3>
New Welcome message : <input type="text" #newWelcomeMessage (input)="0"/>
<h3>
{{newWelcomeMessage.value}}
</h3>
`,
styles: [`
h3 {
font-size:28px;
}`]
})
export class HelloWorldComponent implements OnInit {
welcomeMessage = 'Welcome to Angular Data Binding Example!!';
constructor() { }
ngOnInit() {
}
}
Output:
Safe Navigation Operator ( ?. ) in Interpolation
Safe Navigation Operator ( ?. ) is an angular template expression operator, safe navigation operator prevents angular from throwing an exception when there is a null or undefined property. Safe Navigation Operation “?.” can also be called as “Elvis Operator”. Elvis Operator prevents the angular engine from complaining if you try to access values on objects that are null or undefined. The statement will simply be ignored instead of causing an error when the property you’re trying to access is on a null or undefined
Syntax
Object?.path
Let’s understand the usage of Safe Navigation Operator
create a new component safenav ( ng generate component safenav )
safenav.component.ts
import { Component, OnInit } from '@angular/core'; import { User } from './user.model'; @Component({ selector: 'app-safenav', templateUrl: './safenav.component.html', styleUrls: ['./safenav.component.css'] }) export class SafenavComponent implements OnInit { user1 = new User('TestUser2','IN'); user2 : User; constructor() { } ngOnInit() { } }
In the above code, we have created a new component safenav and create two users (user1, user2).
We have created a new object for user1 and have passed the value to its constructor and for user2 we have just declared it as a User type.
user.model.ts
export class User { public name: string; public city: string; constructor(name: string, city: string) { this.name = name; this.city = city; } }
safenav.component.html
<h3>User 1</h3> Name :<p>{{user1.name}}</p> City :<p>{{user1.city}}</p> <h3>User 2</h3> Name :<p>{{user2.name}}</p> City :<p>{{user2.city}}</p>
Output:
Upon running the above code we will be getting the undefined error, since the user2 is not defined.
ERROR TypeError: Cannot read property 'name' of undefined at Object.eval [as updateRenderer] (SafenavComponent.html:6) at Object.debugUpdateRenderer [as updateRenderer] (core.js:14735) at checkAndUpdateView (core.js:13849) at callViewAction (core.js:14195) at execComponentViewsAction (core.js:14127) at checkAndUpdateView (core.js:13850) at callViewAction (core.js:14195) at execComponentViewsAction (core.js:14127) at checkAndUpdateView (core.js:13850) at callWithDebugContext (core.js:15098)
We can make Angular not to throw an exception by adding the Safe Navigation Operator in the interpolation
<h3>User 1</h3> Name :<p>{{user1?.name}}</p> City :<p>{{user1?.city}}</p> <h3>User 2</h3> Name :<p>{{user2?.name}}</p> City :<p>{{user2?.city}}</p>
app.component.html
<app-safenav></app-safenav>
Output :
We can also us ngIf directive to achieve the same functionality
<h3>User 1</h3> Name :<p *ngIf="user1">{{user1.name}}</p> City :<p *ngIf="user1">{{user1.city}}</p> <h3>User 2</h3> Name :<p *ngIf="user2">{{user2.name}}</p> City :<p *ngIf="user2">{{user2.city}}</p>
The other alternative is using “&& operator”
<h3>User 1</h3> Name :<p>{{ user1 && user1.name}}</p> City :<p>{{ user1 && user1.city}}</p> <h3>User 2</h3> Name :<p>{{ user2 && user2.name}}</p> City :<p>{{ user2 && user2.city}}</p>
Both ngIf and && Operator approaches are valid only but it will become complex when the property path is long. Say for example if we want to protect null or undefined for a longer path such as obj1.obj2.obj3.obj4 in those it is not advisable to use ngIf or && operator and it is better to go with Safe Navigation Operator.
Angular Escape HTML
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
Let’s understand the usage of Escape HTML
create a new component escape ( ng generate component escape)
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-escape', template: ` <h3><u>Escape Simple HTML</u></h3> <p>{{hello}}</p> <h3><u>Escape Script</u></h3> <p>{{script}}</p> <h3><u>Escape Curly braces</u></h3> <p ngNonBindable>{{text}}</p> `, styles: [` h3 { font-size:28px; }`] }) export class EscapeComponent implements OnInit { hello = '<em> Hello World </em>'; script = '<script> alert("Danger !!!") </script>'; text = '1234567'; constructor() { } ngOnInit() { } }
Let’s understand what happens in the above code
- Simple HTML – The HTML “<em> Hello World </em>” is rendered as a string <em>Hello World</em> and not as Hello World
- Escape Script – The <script> tag contains the alert message alert(“Danger !!!”), angular escaped the script tag and rendered it as a string rather than interpreting it and displaying an alert message Danger!!!
- Escape Curly braces – In Order to Escape curly braces we have used the ngNonBindable directive, the ngNonBindable directive tells Angular not to compile or bind the contents of the current DOM element and hence we will be getting the output as {{text}} rather than 1234567
app.component.html
<app-escape></app-escape>
Output:
Source Code
The source code attached will not be having the dependencies (node_modules), please use the command npm install to get the dependencies installed.
Leave a Reply