Angular Interpolation

In this article, we will learn the concept of Interpolation in Angular.

What is Angular Interpolation

Angular Interpolation allows us to add expressions as a part of any string literal, which we use in our HTML. The angular evaluates the expressions into a string and reinstates them in the original string and refreshes the template view.

Angular interpolation is also known by the name string interpolation. Because you incorporate expressions inside another string.

Syntax

{{ }} (double curly braces) in the template to signify the interpolation. The syntax is as shown below

{{ expression }}

The content inside the double braces is called Template Expression.

The Angular evaluates the Template Expression and converts it into a string then it replaces the Template expression with the result in the original string. Whenever the template expression changed, the Angular updates automatically the original string again.

angular interpolation

Example

Create a new angular application using the following command

ng new demo

Open the app.component.html and add the following code

{{title}}

Open the app.component.ts and add the following code

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Interpolation Example';
}

Run the app now. You will see the response “Interpolation Example” on your screen.

If you change the title in the component class, Angular updates the view accordingly.

The interpolation is much more important than just getting the property of the component. You can use it to call any method on the component class or to do some math operations etc.

Key points of an Angular Interpolation

Interpolation is one-way binding

Interpolation is one-way binding as values move from the component to the template. When the component values are changed, Angular updates the view template, But if the values are changed from view components are not updated.

Should not change the state of the app

The Template expression shouldn’t change the state of the application. The Angular uses Template expression to fetch the values from the component and populate them on the view. If it will change the component values, then the rendered view would be incompatible with the model.

That means we can’t make use of the following

  • Assignments (=, +=, -=, )
  • Keywords like new, typeof, instanceof, etc
  • Chaining expressions with ; or ,
  • The increment and decrement operators ++ and
  • bitwise operators such as | and &

The expression must be in a string

Interpolation expression must result in a string. If we deliver an object, it will not work. If you want to bind another expression (for example – boolean), then Property Binding is the most suitable option.

Works for Properties & not for attributes

Interpolation and property binding can be set only for properties, not for attributes. For Attributes, we can use attribute binding.

Examples of interpolation

You can use interpolation to call a method from the component, Concatenation two strings, perform some math operations or change the property of the DOM element like font, color, etc.

Invoke a method in the component

We can call the component’s methods using interpolation.

//Template

{{getName()}}


//Component
firstName = 'Ghanshyam';
getName(): string {
 return this.firstName ;
}

Concatenate two string

<p>Welcome to {{companyName}}</p>
<p>{{ 'Hello & Welcome to '+ ' Angular Interpolation '}}</p>
<p>Welcome {{firstName}}, {{lastName}} to {{companyName}}</p>
<p>Welcome {{getFirstName()}}, {{getLastName()}} to {{companyName}}</p>

Mathematical operations

<h2>Math Operations</h2>

<p>20x50 = {{20*50}}</p>
<p>Largest: {{maxFrom(50, 100)}}</p>

//Component
maxFrom(first: number, second: number): number {
 return Math.max(first, second);
}

Bind element property

We can use it to bind to a property of the HTML element, a component, or a directive. in the following code, we will bind to the style.color property of the <p> element. We can bind to any property like below which accepts a string.

<p>this is <span class = "{{colorAttr}}">red</span></p>
<p style.color={{colorAttr}}>This is red</p>

Bind to an image src

<img src="{{itemImageUrl}}">

href

<a href="/exam/{{examId}}">{{examName}}</a>

Template reference variable

we can also use the template reference variable. The below example creates a template variable #companyName to an input box. You can use it to get the value of the input field {{companyName .value}}

<label>Enter Your Company's Name</label>
<input (keyup)="0" #companyName>
<p>{{companyName.value}} </p>

We can also use (keyup)=”0″ on the input element. It’s nothing but demands the angular run the change detection, which in turn refreshes the view.

//Template
 
<p>Companies</p>
<ul>
  <li *ngFor="let cmp of companies">
    {{ cmp.name }}
  </li>
</ul>
 
//Component
  companies= [
    new company(1, 'Vision'),
    new company(2, 'Optimum')
  ]
 
class company {
  code:string
  name:string
 
  constructor(code,name) {
    this.code=code;
    this.name=name
  }
}

Cross-site Scripting or XSS

An Angular Sanitizes everything before inserting it into the DOM elements, thus restricting Cross-Site Scripting Security bugs (XSS). For example values from the attribute, style, class binding, component property, or interpolation, etc are sanitized. The script in the below example is not calling but is shown as it is.

//Template
<p>{{scriptData}}</p>
<p>{{divData}}</p>

//Component
scriptData = '<script>alert("this is alert message code.")</script>'
divData = '<div>this is a div tag.</div>';

NgNonBindable

The ngNonBindable is used to tell Angular not to compile or bind the contents of the current DOM element. For example, we don’t need to evaluate any expression but need to show it as it is.

<p>Evaluated value: {{variable}}</p>
<p ngNonBindable>Do not evaluate: {{variable}}</p>


<p>Angular uses {{ variable }} for Interpolation</p>
<p ngNonBindable>Angular uses {{ variable }} for Interpolation</p>

Use Pipes

You can use Pipes to transform the expression result. For example convert to an uppercase, date formats, adding currency symbols, etc.

<p>uppercase string: {{title | uppercase}}</p>
<p>pipe chain: {{title | uppercase | lowercase}}</p>
<p>json string: {{items | json}}</p>

The safe navigation operator ( ? )

You can use a safe navigation operator ( ? ) to protect us against null and undefined values.

The below code throws an error because there is no companyName.

<p>The company name is: {{company.companyName}}</p>

TypeError: Cannot read property 'companyName' of undefined

Using a safe navigation operator is to solves the errors like above. Angular replace that with an empty string.

<p>The company name is {{company?.companyName}}</p>

The non-null assertion operator

The Typescript enforces the strict null checking if we enable the –strictNullChecks flag in our tsconfig.json. The type checker throws an error if it can not be determined whether a variable will be null or undefined at runtime.

We can use the non-null assertion operator to tell typescript not to throw any compilation errors.

Note that it’s a compile-time functionality & not for runtime.

The company name is: {{company!.companyName}}

1 Comment

  1. Xavier

    “The Angular” is never used in English. The definite article “the” cannot be used here. You can say “The Angular software”, “the angular syntax”, “the angular interpolation” etc but never “the angular”. This sentence doesn’t make sense – “It’s nothing but demands the angular run the change detection,”
    Thank you for the article, hope this helps and have a great day.

    0
    0
    Reply

Submit a Comment

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

Subscribe

Select Categories