When creating any new Angular project, you’ll see the default in the app.component.html file, thing, which in the tutorial about Angular’s Component I call it placeholder {{title}}, actually its name must be the Interpolation directive, which is used to display the data from the Component class in this Component’s template file. In this tutorial, we will learn more about this Interpolation directive!
First, I will create a new Angular project as an example:
For simplicity, I will use AppComponent in src/app/app.component.ts file with template property for @Component decorator as follows:
1 2 3 4 5 6 7 8 9 10 11 12 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div>Hello {{ title }}</div> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-interpolation'; } |
Result:
As you can see to declare an Interpolation directive in Angular, we will use two curly braces, inside, they can be declared the name of a property in the Component.
As in our example above, the title is a property in AppComponent class and Angular will evaluate this Interpolation directive with the value of the title property.
We can also get the relevant information of the title property in Interpolation, for example getting the length of this property:
1 2 3 4 5 6 7 8 9 10 11 12 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div>Hello {{ title.length }}</div> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-interpolation'; } |
Or uppercase the title property:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div>Hello {{ title.length }}</div> <div>Hello {{ title.toUpperCase() }}</div> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-interpolation'; } |
Result:
You can also perform calculations, concatenate strings with the Interpolation directive.
Examples are as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div>{{ 2 + 5 }}</div> <div>{{ "Hello, " + "Khanh" }}</div> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-interpolation'; } |
Result:
Or call a method that returning value in Component with Interpolation directive:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <div>{{ "Hello, " + getName() }}</div> `, styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angular-interpolation'; getName() { return 'Huong Dan Java'; } } |
Result: