How can I write data attributes using Angular?

AngularAngular2 Template

Angular Problem Overview


I feel like I am missing something. When I try to use a data attribute in my template, like this:

<ol class="viewer-nav">
    <li *ngFor="#section of sections" data-sectionvalue="{{ section.value }}">
        {{ section.text }}
    </li>
</ol>

Angular 2 crashes with:

> EXCEPTION: Template parse errors: Can't bind to 'sectionvalue' since > it isn't a known native property (" > > >

  1. ->]data-sectionvalue="{{ section.value }}">{{ section.text }}

I'm obviously missing something with the syntax, please help.

Angular Solutions


Solution 1 - Angular

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>
See also :

Solution 2 - Angular

About access

<ol class="viewer-nav">
    <li *ngFor="let section of sections" 
        [attr.data-sectionvalue]="section.value"
        (click)="get_data($event)">
        {{ section.text }}
    </li>  
</ol>

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSerj SaganView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularMax ShmelyovView Answer on Stackoverflow