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';

@Component({
    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) {
        alert(e.target.id);
    }
}

👉 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">
      <thead>
          <tr>
              <th>Employee Name</th>
              <th>Age</th>
              <td>Status</td>
          </tr>
      </thead>
      <tbody>
          <tr *ngFor="let myVar of employees;">
              <td>{{myVar.name}}</td>
              <td>{{myVar.age}}</td>
                  
              <td *ngIf="myVar.age >= 20;">
                <label id="{{'Clear ' + myVar.id}}" (click)="showID($event)">Clear</label>
              </td>
              <td *ngIf="myVar.age <= 20;">
                <label id="{{'Hold ' + myVar.id}}" (click)="showID($event)">Pending</label>
              </td>
          </tr>
      </tbody>
  </table>
</div>

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}}"

and

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

Well, that’s it. Thanks for reading.

← PreviousNext →