What is Interpolation in Angular ?
Interpolation is used for one-way data binding in Angular Framework. It embeds an expression into an HTML template. By default, the expression should be surrounded by {{ and }}. This expression is called a Template Expression.
Syntax:
{{expression}}
An Angular evaluates an expression surrounded by {{ and }} and then converts a result to a string and assigns it to an element or directive property.
Syntax:
{{expression}} output => string
Example:
In this example, we will write some arithmetic expressions in the app.component.html file by using interpolation.
app.component.html:
<html>
<head><title>Interpolation Demo</title></head><body><p> 8 + 7 = {{ 8+ 7 }} </p><p> 7 * 3 = {{ 7 * 3 }} </p><p> {{ "8 + 7= "+ 8+ 7 }} </p><p> {{ "8 + 7= "+ (8 + 7) }} </p></body></html>
Output:
→ The above example evaluates an arithmetic expression and converts the result into a string.
Example:
In this example, we will define a property in the app.component.ts file and render that property value by using {{ popertyname}} in the view template i.e., app.component.html file.
app.component.ts:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public name="Spring Java";}
app.component.html:
<h2>
Welcome {{name}}</h2>
Output:
Example:
In this example, we will call the JavaScript property and method by using interpolation.
app.component.ts:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public name="Spring Java";}
app.component.html:
<h2>
{{name.length}}</h2><h2> {{name.toUpperCase()}}</h2>
Output:
Example:
In this example, we will create a method in the component class and call that method by using interpolation in the view template.
app.component.ts:
import { Component } from '@angular/core';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { public name="Spring Java"; greeting(){ return" Hello "+this.name; }}
app.component.html:
<h2>
{{greeting()}}</h2>
Output:
These things that are invalid for interpolation are:
<p>{{ num++ }} </p>
<p>{{ num += 1}} </p><p>{{ count}} </p><p>{{ typeof(num) }} </p><p>{{ Date.now()}} </p><p>{{ window.name}} </p><p>{{ console.log('This is an error')}} </p>
Conclusion
This topic is explained:
• What is interpolation in Angular?
• What is the syntax of interpolation?
• How to use interpolation for arithmetic expressions?
• How to call component property by using interpolation?
• How to call JavaScript property and method by using interpolation?
• How to call the component method by using interpolation?
• What are the things that are invalid for interpolation?