The Angular 7 String Interpolation is used to render dynamic data on the HTML template at the user end. In string interpolation, the value flows in one direction, i.e., from components to html elements. String interpolation is used for one way data binding. However, Angular’s data binding is a valuable feature that allows us to communicate between the component and its view.
When we use interpolation and change the value of the bound field, the changes are also reflected on the page/HTML. The component HTML template uses an object of the component class as the data context for its template – that’s why the value that is intended to be bound on the view must be allocated to the component class field.
The structure of a basic Angular project is:
component.css
- styles or CSS based upon our requirements is specified in this file.component.html
- HTML code is specified in this file.component.spec.ts
- file is used for testing.component.ts
- consists of business logic for linking the code to HTML. Values defined in this file can be referenced in the HTML file using curly brackets to enable data binding.In order to successfully implement string interpolation, modify the component.ts
file, and the changes will be reflected in component.html
file as it will fetches the data from component.ts
file for its HTML template
This is a basic simple implementation of string interpolation specifying changes in only the app.component.ts
and app.component.html
file. The comments in the code identify some of the different operations in interpolation.
import { Component, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Edpresso Readers";
Myname = "Shanzay Gauhar";
city = "I live in Lahore";
//binding properties in interpolation
shot = {
name: "String Interpolation",
date: "29 April,2021",
country: "Pakistan"
};
}
<div><!--Simple interpolation--><h2> Hello {{name}}!</h2></div><div><!--Concatenation of fields in interpolation: variable + variable-->My name is {{Myname +". " + city}}<!--Another concatenation Example: static + variable --><br>{{'Hope you are all fine! ' + name}}</div><div><!--basic without any error handling-->Name of the shot: {{shot.name}}<br><!--error handling: ensures presence of the property value's in an object-->Last Modified: {{shot && shot.date}}<br><!--safe navigation operator: it securely connects internal fields-->Country: {{shot?.country}}</div>
In the example above, {{ variable }}
) are used to specify interpolation.
String interpolation is a good substitute for property binding. It is preferred when we have to perform string concatenation. while property binding is more suitable for setting an element property to a non-string data value.