Angular Interpolation: Display Data in Your Templates

Learn Angular interpolation: Display dynamic data in your templates using double curly braces {{ }}. Simple guide with examples.



Interpolation in Angular

Interpolation is used for one-way data binding in Angular, embedding expressions into the HTML template. By default, expressions are surrounded by {{ and }}. These expressions are also known as template expressions.

Syntax

Example: Basic Syntax

{{ expression  }}

Angular evaluates the expression within {{ and }}, converts the result to a string, and assigns it to an element or directive property.

Examples

The following example shows how arithmetic expressions are evaluated and converted into strings:

Example: Interpolation

<p> 2 + 3 =  {{ 2 + 3  }} </p> <!-- output: "2 + 3 = 5" -->
<p> 3 * 4 =  {{ 3 * 4  }} </p> <!-- output: "3 * 4 = 12" -->
<p>  {{ "3 + 3 != " + 3 + 3  }} </p> <!-- output: "3 + 3 != 33" -->
<p>  {{ "3 + 3 = " + (3 + 3)  }} </p> <!-- output: "3 + 3 = 6" -->

Accessing Component Data

Interpolation expressions can access public properties or methods of a component class, but not private or protected members.

Component Class Example:

Example: Component Class

export class InterpolationDemo implements OnInit {
public text: string = "Hello";
public caption: string = "Click Here!";
num: number = 5;
randomNums: number[] = [4, 9, 11, 3, 5, 18, 34, 22, 100];

private count: number = 0; 

ngOnInit(): void {}

getCurrentTime(): any {
return Date.now();
}
}

The HTML template for the above component can use its members as expressions in interpolation:

Example: Using Component Data

<p> {{ text  }}</p>
<p> {{ num  }}</p>
<p> {{ getCurrentTime()  }}</p>
<button innerText= {{caption }}></button>

You can also use template input variables in interpolation:

Example: Input Variable

<ul>
<li *ngFor="let rndNum of randomNums"> {{ rndNum  }}</li>
</ul>

Limitations

Most JavaScript expressions are valid in template expressions, except for the following:

  • Assignment, bitwise, increment, and decrement operators (=, +=, =-, |, &, ++, --, !, ?., etc.)
  • new, typeof, instanceof, etc.
  • Chaining expressions with ; or ,
  • Some ES2015+ operators

Example: Invalid Interpolation

Example: Invalid Interpolation

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

Configuring Interpolation Delimiters

By default, Angular uses {{ and }} as delimiters, but you can configure different delimiters using the interpolation option in the @Component decorator.

Example: Custom Delimiter

@Component({
selector: 'app-custom-delimiter',
interpolation: ['?', '?'],
})
export class CustomDelimiterComponent {}

Conclusion

Interpolation is a simple way to achieve one-way data binding using template expressions in Angular.