Unable to use img ng-src (Can't bind to ng-src since it isn't a known property of img)
Asked Answered
M

2

7

I have an Angular project with Webpack, and I am trying to use an img tag with ng-src, per the Angular docs here:

https://docs.angularjs.org/api/ng/directive/ngSrc

I am trying to have a variable in the image source like so:

<img ng-src="assets/images/{{row.imagePath}}.png" width="1" height="1" />

However, when I run ng serve, I get the following errors in the browser console:

zone.js:569 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ng-src' since it isn't a known property of 'img'.

I have Googled and found others using ng-src without issues with Angular + Webpack, so I am not sure why it is not working in this project. Thank you.

Macneil answered 10/5, 2017 at 2:16 Comment(0)
M
20

You can use the [attr.src] input to bind to native html properties.

In your component.ts file

Lets say you have a list of items of type ListItem, the ListItem class would need to expose an imagePath property. Like so

export class ListItem {
    public imagePath: string;
    // ....
}

@Component({
  templateUrl: './your/template/example.html',
})
export class YourComponent {
    listItems: ListItem[];
    //...
}

In your template

<div *ngFor="item in listItems">
    <img [attr.src]="item.imagePath" width="1" height="1" />
</div>

Hope this helps!

Marita answered 10/5, 2017 at 2:58 Comment(2)
Worked perfectly. Thank you!Macneil
Where is one supposed to find the list of bindable attributes of a HTML tag? a search for "img" on angular.io is not giving me comprehensive docs on it..Halide
U
2

What worked for me was using just src. Example:

    <td><img src="assets/{{elemento.foto}}" alt="(sin foto!)" class="img-responsive"/></td>
Ultra answered 16/4, 2018 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.