【问题标题】:Angular: data binding to data attributes does not workAngular:数据绑定到数据属性不起作用
【发布时间】:2020-11-03 16:16:42
【问题描述】:

我有以下代码,我在其中添加数据属性data-description

<span *ngFor="let item of images">

<img
        src="{{ item.url }}"
        alt="{{ item.name }}"
        data-description="{{ item.description }}"
      />
</span>

生成的html代码是

<span>    
    <img
            src="url/here"
            alt="name/here"
          />
    </span>

如您所见,data-description 根本不显示。如何添加?

【问题讨论】:

    标签: angular data-binding


    【解决方案1】:

    您需要绑定到attr 属性,因为data- 规范专门依赖于HTML 属性而不是DOM 元素的属性。

    在你的情况下,你可以拥有

    <span *ngFor="let item of images">
        <img
            [src]="item.url"
            [alt.alt]="item.name"
            [attr.data-description]="item.description"
          />
    </span>
    

    下面是一个示例输出See this Demo

    【讨论】:

      【解决方案2】:

      代替字符串插值,使用绑定,绑定到data-description,使用attr前缀。

      [attr.data-description]="item.description"
      

      我也会将 src 插值更改为道具绑定:

      <span *ngFor="let item of images">
          <img
              [src]="item.url"
              [alt]="item.name"
              [attr.data-description]="item.description"
            />
      </span>
      

      StackBlitz

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-09
        • 1970-01-01
        • 2020-01-02
        • 2018-02-14
        相关资源
        最近更新 更多