Interpolation In Angular
In this article, we learn about interpolation in Angular using examples. To link a component attribute, method, or template reference variable to a string literal in the view, we use interpolation. This is also known as string interpolation. As the data flows from the component to the view, there is only one way from component to view.
What is Angular Interpolation?
We can use interpolation to incorporate expressions as part of any string literal in our HTML. The expressions are evaluated into a string, which is then replaced in the original string and the view is updated. Interpolation is available anywhere a string literal is used in the view.
String interpolation is another name for angular interpolation. Because you use expressions within another string.
Syntax for interpolation:
The interpolation is indicated by the {{}} (double curly brackets) in the Angular template. The syntax is as follows:
{{ templateExpression }}
Example of Interpolation:
ng new angular-interpolation
{{title}}
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular Interpolation Example';
}
Notes
Interpolation is one-way binding
The application state should not be changed
- Assignments (=, +=, -=, …)
- Keywords like new, typeof, instanceof, etc
- Chaining expressions with ; or ,
- The increment and decrement operators ++ and --
- bitwise operators such as | and &
The outcome of the expression must be a string
Examples of Interpolation :
Invoke one of the component's methods
//Template
{{getTitle()}}
//Component
title = 'Angular Interpolation Example';
getTitle(): string {
return this.title;
}
Concatenate two string
Welcome to {{title}}
{{ 'Hello & Welcome to '+ ' Angular Interpolation '}}
Welcome {{firstName}}, {{lastName}}
Welcome {{getFirstName()}}, {{getLastName()}}
Perform arithmetic operations
100x80 = {{100*80}}
Largest: {{max(100, 200)}}
//Component max(first: number, second: number): number { return Math.max(first, second); }
Bind to a property of an element
<p>Show me <span class = "{{giveMeRed}}">red</span></p>
<p style.color={{giveMeRed}}>This is red</p>
Bind image source
<img src="{{itemImageUrl}}">
Bind href
<a href="/product/{{productID}}">{{productName}}</a>
Use Pipes
<p>uppercase pipe: {{title | uppercase}}</p>
<p>pipe chain: {{title | uppercase | lowercase}}</p>
<p>json pipe: {{items | json}}</p>