Open In App

String Interpolation in Angular 8

String Interpolation in Angular 8 is a One-way Data-Binding technique that is used to transfer the data from a TypeScript code to an HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view. String interpolation adds the value of a property from the component to the HTML template view.

Syntax:



{{ component_property }}

Approach: 

Example 1: This example illustrates the basic usage of the String Interpolation in Angular 8.






<h1>{{ title }}</h1>




import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = "GeeksforGeeks";
}

Output:

Example 2: This is another example that illustrates the String Interpolation concept where the content of the component is rendered with the help of double curly braces in the view.




<h1 [style.color] = "'green'"
    [style.text-align] = "'center'" >
    {{ title }} : {{ about }}
</h1>




import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = "GeeksforGeeks";
    about = "Computer Science Portal for Geeks";
}

Output:

Example 3: In this example, whenever the “Display Details” button is clicked, the current date and time are printed. From the 5th click, the background color of the text will start changing.




<h3 style="color:#008000;">
  Welcome to GFG!!
</h3>
<button class="btn btn-success"
        (click)="getOnClick()">
  Display Details
</button>
<p *ngIf="btnClickCount%2!=0">
  {{displayText}}
</p>
<div *ngFor="let num of numbersList; let i=index"
     [ngStyle]="{backgroundColor: i>=4 ?'limegreen':'transparent'}"
    [ngClass]="{'whitetext':i>=4}">
    {{num}}
</div>




import { Component } from '@angular/core';
 
@Component({
  selector: '[app-server]',
  templateUrl: './server.component.html',
  styles: [
    `
      .whitetext {
        color: white;
      }
    `,
  ],
})
export class ServerComponent {
  serverId: number = 10;
  serverStatus: string = 'offline';
  secretpassword = 'tuna';
  onclick = false;
  displayText = '';
  btnClickCount = 0;
  numbersList = [];
  count = 0;
 
  getServerStatus() {
    return this.serverStatus;
  }
  getPassword(event: Event) {
    this.secretpassword = (<HTMLInputElement>event.target).value;
  }
 
  getOnClick() {
    this.onclick = true;
    this.count = ++this.btnClickCount;
    this.numbersList.push(new Date());
  }
}

Output:

 


Article Tags :