In this article, we will learn about the angular interpolation.
What is the interpolation
Angular interpolation is used display a component property in the respective view template with double curly braces syntax. We can display all kind of properties data into view e.g. string, number, date, arrays, list or map.
Data binding consist of one way data binding and two way data binding. Interpolation is used for one way data binding. Interpolation moves data in one direction form our components to HTML elements.
Angular Interpolation Syntax
The property name to be displayed in the view template should enclosed in double curly braces also known as moustache syntax. i.e.
app.components.ts
export class AppComponent {
appTitle = 'angular 10 tutorial';
appDescription='Was this post helpful for you about the angular?';
}
app.components.html
<h3>Application title is : {{appTitle}}</h3>
<h4>Application description is : {{appDescription}}</h4>
display view
Angular Interpolation Usages
- Display simple properties - Interpolation can be used to display and evaluate strings into the text between HTML element tags and within attribute assignments.
appTitle = 'angular 10 tutorial';
appDescription = 'Was this post helpful for you about the angular?';
backgroundImgUrl = 'assets/imgs/test.png';
<h3>Application title is : {{appTitle}}</h3>
<h4>Application description is : {{appDescription}}</h4>
<h5><img src="{{ backgroundImgUrl }}" style="height: 400px;"></h5>
- Evaluate arithmetic expressions - Another usage of interpolation is to evaluate arithmetic expressions present within the curly braces.
<h1>3 + 5 = {{3+5}}</h1>
- Invoke methods and display return values - We can also invoke/call methods on hosting component views within interpolation expressions.
getName(): string {
return 'razr';
}
<h2>Hi, may I have your name?</h2>
<h2>Hi, my name is {{ getName() }}</h2>
- Display array items - We can use interpolation along with ngFor directive to display an array of items.
fruits = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Orange' },
{ id: 3, name: 'Strawberry' }
]
<h2>I like fruits, like </h2>
<ul>
<li *ngFor="let i of fruits">
{{i.name}}
</li>
</ul>
Either we use inline template or separate HTML file for component view, the template data bindings have the same access to the component's properties.
Difference between Interpolation and Property Binding
Interpolation is a special syntax that Angular converts into property binding (pair of square bracket). It's a convenient alternative to property binding.
Another major difference is that to set an element property to a non-string data value, we must use property binding.
In this example, OK
button will be disabled or enabled based on the value of isDisabled
. On the other side, Cancel
button will always be disabled irrespective of the property value.
isDisabled: boolean = true;
<button [disabled]='isDisabled'>OK</button>
<button disabled='{{ isDisabled }}'>Cancel</button>