【问题标题】:How can I write data attributes using Angular?如何使用 Angular 编写数据属性?
【发布时间】:2016-04-05 04:49:25
【问题描述】:

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

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

Angular 2 崩溃:

例外:模板解析错误:无法绑定到“sectionvalue”,因为 它不是已知的原生属性(“

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

我显然在语法上遗漏了一些东西,请帮忙。

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    改用属性绑定语法

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

    另见:

    【讨论】:

    • 如何访问数据属性的值?
    • 请使用一些代码创建一个新问题,以演示您要完成的工作。
    • 这应该是 Google 对 Can't bind to '' 的第一答案,因为它不是 '' 查询的已知属性。这条评论可能有点帮助......
    • @netzaffin 这是一个有用的答案,但我多次遇到无法绑定错误,这是第一次这是实际问题/解决方案。
    • 如何将回调函数也绑定到 data-* 属性?
    【解决方案2】:

    关于访问

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

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 2018-02-14
      • 2020-06-05
      • 2018-06-11
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多