Concatenate String with Variable inside HTML element tag in Angular 6

In Angular 6, 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 populate 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);
    }
}
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 technique. The id of each label has a string value (like Clear or Hold) concatenated with the id of an employee.

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.

← Previous



Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.

Enter your email id

Delivered by FeedBurner

Related Posts: