Solving attribute binding issue for Angular

Last Updated On

Foreword:

If you’re working with Angular, you should have good familiarity with the databinding idea (properties binding, event binding, two-way databinding). Here is a link for databinding official documentation.

The issue:

I’ve run into issue when I needed to bind native HTML data- attribute from view to the logic inside the Typescript file. When I tried to bind

<ul class="header-nav">
    <li *ngFor="#navItem of navItems" [data-item-id]="navItem.id">{{navItem.description}}</li>
</ul>

I’ve got an error:

EXCEPTION: Template parse errors: Can't bind to 'data-item-id' since it isn't a known native property...

The Solution:

Each HTML Attribute should be prefixed with the special attr keyword. From the code perspective it will look like this:

<ul class="header-nav">
    <li *ngFor="#navItem of navItems" [attr.data-item-id]="navItem.id">{{navItem.description}}</li>
</ul>

Since Angular has another way of syntax for properties binding, functionality above can be rewritten in the following way:

<ul class="header-nav">
    <li *ngFor="#navItem of navItems" attr.data-item-id="{{navItem.id}}">{{navItem.description}}</li>
</ul>

Conclusion:

Don’t forget to put attr word in a front of HTML attribute if you want to bind this attribute with TypeScript. Happy coding 🙂