What is interpolation in Angular?
Interpolation in Angular is a one-way data binding technique that allows you to display component data (properties) directly within your HTML templates. It uses double curly braces `{{ }}` to bind properties from the TypeScript component class to the HTML view.
How Interpolation Works
When Angular encounters {{ expression }} in your template, it evaluates the expression and converts the result into a string, which is then inserted into the DOM. This process happens automatically whenever the component's data changes, ensuring that the view always reflects the latest state of your component properties. It's primarily used for displaying strings, numbers, booleans, and results of simple expressions.
Key Features and Use Cases
- One-way data binding: Data flows from the component to the view.
- Displays component property values directly in the template.
- Can evaluate simple JavaScript expressions, arithmetic operations, and method calls (that return a value).
- Automatically updates the view when the bound property's value changes.
- Can be used for text content, attribute values (though property binding
[attr.attribute]is often preferred for attributes), and more.
Example
Consider a component with a property userName and a method greetUser():
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
template: `
<p>Welcome, {{ userName }}!</p>
<p>Message: {{ greetUser() }}</p>
<p>Current year: {{ 2023 + 1 }}</p>
`,
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
userName: string = 'Alice';
greetUser(): string {
return 'Hello from ' + this.userName + '!';
}
}
In this example, {{ userName }}, {{ greetUser() }}, and {{ 2023 + 1 }} are all examples of interpolation. Angular will render them as:
<p>Welcome, Alice!</p>
<p>Message: Hello from Alice!</p>
<p>Current year: 2024</p>