Angular Binding to non-native Attribute

One of the typical gotcha is that while using bootstrap with Angular, some of the bootstrap attributes can not be bound directly.

Normally when you doing simple binding in Angular, this is what you do:

<img md-card-image class="img-responsive img-rounded" 
    src="{{user.profilePic}}"
     onerror="this.style.display='none'">

You bind the user.profilePic to attribute “src” of “img” element, which is fine.

When using bootstrap, a example is using carousel, and trying to set carousel slide to indicator, where the attribute is not native to element “li”.

Let say you want to generate corresponding number of slide indicator to number of pictures you want to display.

<ol class="carousel-indicators">
  <li data-target="#myCarousel" data-slide-to="{{i}}" 
     class="{{i == 0 ? 'active' : ''}}" 
     *ngFor="let pic of galleryPics;let i = index"></li>
</ol>

while binding directly to “class” attribute which is native to “li” element, it cause an error binding to “data-slide-to” attribute.

Can't bind to 'data-slide-to' since it isn't a known property of 'li'.

So what you really should do is to tell Angular that you know there is a attribute of given element that you want set the binding to. [attr.data-slide-to]=”i”

<ol class="carousel-indicators">
  <li data-target="#myCarousel" [attr.data-slide-to]="i" 
      class="{{i == 0 ? 'active' : ''}}" 
      *ngFor="let pic of galleryPics;let i = index"></li>
</ol>

Leave Comment

Your email address will not be published. Required fields are marked *