首页 文章

Angular 2数据属性

提问于
浏览
157

我觉得我错过了什么 . 当我尝试在 template 中使用 data attribute 时,如下所示:

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

Angular 2 崩溃:

EXCEPTION:模板解析错误:无法绑定到'sectionvalue',因为它不是已知的本机属性(“] data-sectionvalue =”{}“> {}

我显然遗漏了一些语法,请帮忙 .

2 回答

  • 344

    关于访问

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

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

    请改用属性绑定语法

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

    要么

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

    另见How to add conditional attribute in Angular 2?

相关问题