
In this example, we’ll learn about string interpolation with an Angular 10 example.
Open your Angular component file and define the following TypeScript string variables:
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
// Initialize some TypeScript variables here
userId = '1';
lastName = 'Michell';
getLastName() {
return this.lastName;
}
}
We also define a method that simply returns the lastName
variable.
Now that we have some TypeScript variables defined in the component’s class, how to display them in the corresponding component’s template?
Angular uses the concept of interpolation.
Interpolation enables you to use calculated strings into the text between HTML element tags and within attribute values via template expressions.
What’s Angular Interpolation {{...}}
?
Interpolation simply means putting expressions into marked-up text. By default, interpolation uses as its delimiter the double curly braces, {{
and }}
.
Angular String Interpolation Example
Now, let’s continue with our example.
Next, in the src/app/app.component.html
file add the following markup:
{{ 'User' }} with identifier {{ userId }} and last name {{ getLastName() }}.
We use braces for using string interpolation to display the values from the component’s variables in the template. Angular replaces that expression or variable’s name with the string value of the corresponding component property. We can either interpolate variables or methods that return a specific value.
Leave a Reply