String Interpolation in Angular 8
String Interpolation in Angular 8
String interpolation is a one-way data-binding technique which is used to output the data from a typescript code to HTML template. It uses the template expression. It uses the template expression in double curly braces {{ }} to display the data from component to view.
String interpolation adds the value of the property from the component. It allows the user to bind the value to a UI element.
Interpolation binds the data one-way.
Syntax:
{{data}}
We have firstly created an Angular project using Angular CLI.
The syntax of binding a field using double curly braces is called Binding Expression.
String interpolation uses template expressions in double curly {{ }} braces to display data from the component, the syntax {{ }}, also known as moustache syntax. The {{ }} contains a javascript expression which can be run by angular, and the output will be inserted into the HTML.
If we put {{5+5}} in the template ten will be inserted into the HTML.
Open the file app.component.ts and use the following code within the file:
import {Component} from ‘@angular/core’; @Component({ selector: ‘app-root’, templateUrl:’./app.component.html’, styleUrls: [‘./app.component.css’] }) export class AppComponent { title=’string interpolation in tutorialandexample’; }
Now, open app.component.html file in the project and use the following code to see String Interpolation.
{{ title}}
Now, open Node.js command prompt and run the ng serve –open to open the localhost: 4200 to see the output of the program.
String interpolation can be used to solve some other expression too. Let's see another example.
Example:
Update the app.component.ts file with the following code:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Data binding example using String Interpolation'; numberA: number = 10; numberB: number = 20; }
app.component.html:
Calculation is : {{ numberA + numberB }}
Output:
We can use the same application in another way also.
app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Data binding example using String Interpolation'; numberA: number = 10; numberB: number = 20; addTwoNumbers() { return this.numberA + this.numberB; } }
app.component.html:
Calculation is : {{ numberA + numberB }}
Output: