Open In App

How to use javascript function in string interpolation in AngularJS ?

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 :

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>
<hr/>

Output : 

Example 2: (Custom Functions)




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.




<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.


Article Tags :