Interpolation in Angular 2
Interpolation is used for one-way data binding in Angular. It embeds an expression into the HTML template. By default, expression should be surrounded by { and }. This expression is also known as template expression.
{{ expression }}
Angular evaluates an expression surrounded by { and } and then converts a result to a string and assigns it to an element or directive property.
{{ expression }} output=> string
The following example evaluates an arithmetic expression, converts the result into a string.
<p> 2 + 2 = {{ 2 + 2 }} </p> <!-- output: "2 + 2 = 4" -->
<p> 2 * 3 = {{ 2 * 3 }} </p> <!-- output:"2 * 3 = 6" -->
<p> {{ “2 + 2 != ”+ 2 + 2 }} </p> <!-- output:"2 + 2 != 22" -->
<p> {{ “2 + 2 = ”+ (2 + 2) }} </p> <!-- output:"2 + 2 = 4" -->
The context of the interpolation expression is a component class. It means it can access public properties or methods of a component class. However, it cannot access private or protected members.
Consider the following component class.
export class InterpolationDemo implements OnInit {
public text: string = "Hello";
public caption: string = "Click Me!";
num: number = 0;
randomNums: number[] = [3, 6, 7, 8, 1, 122, 44, 67, 790];
private count:number = 0;
ngOnInit(): void {
}
getCurrentTime(): any {
return Date.now();
}
}
The HTML template of the above component can use members as an expression in interpolation, as shown below.
<p>{{ text }}</p>
<p>{{ num }}</p>
<p>{{ getCurrentTime() }}</p>
<button innerText={{caption}}></button>
It can also use template input variable, as shown below.
<ul>
<li *ngFor="let rndNum of randomNums">{{rndNum}}</li>
</ul>
Most JavaScript expressions are valid template expression except the following: - Assignment, bitwise, increment and decrement perators (=,+=, -=, |, &, ++, –,!, ?. etc.) - new, typeof, instanceof, etc. - chaining expression with ; or , - some ES2015+ operators
The following will give a compile-time error.
<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>
Configure Interpolation Delimiter
By default, Angular use { and } delimiter. However, you can configure it and specify different delimiter using the interpolation option in the @Component decorator.
For example, the following configures ? and ? as starting and ending interpolation delimiter.
@Component({
selector: 'app-event-binding-demo',
interpolation:['?','?'],
})
Thus, interpolation is an easy way of one-way data binding using template expression.