Accessing Data Attributes in Angular

Set data attributes (eg data-item) on an HTML element and then read the values using the getAttribute method or the dataset property.

Setting Data Attributes

Here we assign a fixed value of "component" to the category data attribute, and use the built-in Angular attr directive to assign the values of the catId and color variables to the catalog-id and color data attributes.

data-attribute.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-data-attribute',
  template: `
    <section
      #prod
      id="product"
      data-category="component"
      [attr.data-catalog-id]="catId"
      [attr.data-color]="color">
      Some Cool Product
    </section>

    <p>
      <button #btn (click)="order(prod.dataset.catalogId, prod.dataset.color)">
        Order this {{prod.getAttribute('data-category')}}
      </button>
    </p>

    <p>
      {{confirmation}}
    </p>
  `
})
export class DataAttributeComponent  {
  catId = 'ACV126673';
  color = 'blue';
  confirmation: string;

  order(catalogId: string, color: string) {
    this.confirmation = `Ordered product ${catalogId} in ${color}.`;
  }
}

Reading Data Attributes

We can read the data attribute values using the dataset property or the getAttribute method on the prod template reference variable.

data-attribute.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-data-attribute',
  template: `
    <section
      #prod
      id="product"
      data-category="component"
      [attr.data-catalog-id]="catId"
      [attr.data-color]="color">
      Some Cool Product
    </section>

    <p>
      <button #btn (click)="order(prod.dataset.catalogId, prod.dataset.color)">
        Order this {{prod.getAttribute('data-category')}}
      </button>
    </p>

    <p>
      {{confirmation}}
    </p>
  `
})
export class DataAttributeComponent  {
  catId = 'ACV126673';
  color = 'blue';
  confirmation: string;

  order(catalogId: string, color: string) {
    this.confirmation = `Ordered product ${catalogId} in ${color}.`;
  }
}

Here is the result.