Concatenate String with Variable inside HTML element tag in Angular 6

← PrevNext →

In Angular, you can use the Interpolation technique to concatenate a string with a variable inside an HTML element tag.

Here’s an example.

I have a table inside my application template. The table rows are populated with data extracted from a JSON array, declared in my component class. Each row has a label attached (based on a condition) and the id of each label will have a string concatenated with a variable.

The Application Component (app.component.ts)
import { Component, OnInit } from '@angular/core';

    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
export class AppComponent {
    ngOnInit () {  }

    // The JSON array.
    employees: any [] = [
        { 'id': '001', 'name': 'Alpha', 'age': 37 },
        { 'id': '002', 'name': 'Bravo', 'age': 27 },
        { 'id': '003', 'name': 'Charlie', 'age': 29 },
        { 'id': '004', 'name': 'Delta', 'age': 19 },
        { 'id': '005', 'name': 'Echo', 'age': 32 }

    showID(e) {

👉 Now, you can Dynamically set or assign Label Text on button click in Angular.
Convert textarea data into PDF in JavaScript

The Template (app.component.html)
<div style="width:300px;">
  <table *ngIf="employees">
              <th>Employee Name</th>
          <tr *ngFor="let myVar of employees;">
              <td *ngIf="myVar.age >= 20;">
                <label id="{{'Clear ' + myVar.id}}" (click)="showID($event)">Clear</label>
              <td *ngIf="myVar.age <= 20;">
                <label id="{{'Hold ' + myVar.id}}" (click)="showID($event)">Pending</label>

I have highlighted the portion in the above markup, where I have concatenated a string with the variable myVar.id, inside the <label> tag, using the Interpolation technique. The id of each label has a string value (like Clear or Hold) concatenated with the id of an employee.

What is Interpolation in Angular?

Interpolation is a technique that allows users to bind a value to an element inside the application template. It uses two open and close curly braces like this, {{ some_variable }}.

In my above example,

id="{{'Clear ' + myVar.id}}"


id="{{'Hold ' + myVar.id}}"

← PreviousNext →