• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Angular Interpolation / String Interpolation ( Angular 5 One-Way Data Binding )

May 21, 2018 by javainterviewpoint Leave a Comment

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

  1. Interpolation / String Interpolation (one-way data binding)
  2. Property Binding (one-way data binding)
  3. Event Binding (one-way data binding)
  4. 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/

Angular Interpolation

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:

Angular Interpolation 1

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 :

Angular Interpolation 2

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

  1. Simple HTML – The HTML  “<em> Hello World </em>” is rendered as a string <em>Hello World</em> and not as Hello World
  2. 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!!!
  3. 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:

Angular Interpolation 3

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.

    Download Source Code

Filed Under: Angular Tagged With: Angular Interpolation, Elvis Operator, Escape HTML, Interpolation, moustache syntax, one-way data binding, Safe Navigation Operator, String Interpolation, Template Reference Variables

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·