Search code examples
angularangular2-formsangular2-directives

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


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.


Solution

  • 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!