Open In App
Related Articles

How to use javascript function in string interpolation in AngularJS ?

Improve Article
Save Article
Like Article

String interpolation is basically used to display the dynamic data on an HTML template. It facilitates you to make changes on component.ts file and automatically fetch data from there to the HTML template (component.html file).

So here we create a simple HTML template that uses the string interpolation, and then we write the function that is used inside the string interpolation.

Approach :

  • Create the Angular app to be used.
  • Create a component “DemoComponent”. In the demo.component.ts create some methods that we used inside the string interpolation.
  • Here we are also using the inbuilt JavaScript function inside the string interpolation.

Syntax : 

<h4>Book Price : {{ 'SHOULD BE LOWER CASE'.toLowerCase() }}</h4>


Example 1: (In-Build Functions) Add the below HTML inside angular template and run using “ng serve” and it makes the string lower-case.


<h4>Book Price : {{ 'SHOULD BE LOWER CASE'.toLowerCase() }}</h4>

Output : 

Example 2: (Custom Functions)


import { Component } from '@angular/core';
    templateUrl: './demo.component.html',
    styleUrls: ['./demo.component.css']
export class DemoComponent{
    public Books = [
        {name:"The Pilgrim’s Progress",author:'John Bunyan',price:"13"},
        {name:"Robinson Crusoe",author:'Daniel Defoe',price:"43"},
        {name:"Gulliver’s Travels",author:'Jonathan Swift',price:"33"}
        return "[ " + + " ]";
        return "[ " + + " ]";
        return "[ " + " $" + book.price + " ]";

In the above code, we have created a books array which store the book object and then we have created three functions and we are going to use these three function inside string interpolation to print specific book detail.


<div style="margin-left:100px" *ngFor="let book of Books">
  <h4>Book Name : {{ printBookName(book) }}</h4>
  <h4>Book Author : {{ printBookAuthor(book) }}</h4>
  <h4>Book Price : {{ printBookPrice(book) }}</h4>


Here in the HTML template, we are using a function inside string interpolation to print specific book data.

Last Updated : 03 Jun, 2021
Like Article
Save Article
Similar Reads
Related Tutorials