Open In App

How to use javascript function in string interpolation in AngularJS ?

Improve
Improve
Like Article
Like
Save
Share
Report

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.

example.component.html




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


Output : 

Example 2: (Custom Functions)

demo.component.ts




import { Component } from '@angular/core';
  
@Component({
    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"}
    ]
  
    constructor(){}
  
    printBookName(book){
        return "[ " + book.name + " ]";
    }
    printBookAuthor(book){
        return "[ " + book.author + " ]";
    }
    printBookPrice(book){
        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.

demo.component.html




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


Output:

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
Previous
Next
Share your thoughts in the comments
Similar Reads