Search code examples
angulardata-binding

Angular: data binding to data attributes does not work


I have following code where I add data attribute data-description

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

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

The generated html code is

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

As you can see data-description does not show at all. How can I add it?


Solution

  • You need to bind to attr property as the data- specification depends specifically on HTML attributes rather than properties of DOM elements.

    In your case you can have

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

    Below is a sample output See this Demo

    enter image description here

    enter image description here