4

In Angular1,

<img ng-src="{{imageUrl}}">

This will hide the broken image icon if the imageUrl is empty.

But in Angular2, both

<img src="{{imageUrl}}">

and the equivalent of ngSrc

<img [src]="imageUrl">

still show the small broken image icon as the image placeholder if imageUrl is empty.

What's the actual difference there?

Skyvory
  • 365
  • 7
  • 16
  • set a background image with loading icon for image tag, check out [this answer](http://stackoverflow.com/a/4635498/2435473), or Rather use `alt` tag until image isn't there it will show `Text` from `alt` attribute – Pankaj Parkar Nov 26 '16 at 07:48
  • I don't see here the small broken image icon https://plnkr.co/edit/IhJk0eTdFUZFTsZOfPpT?p=preview – yurzui Nov 26 '16 at 12:57
  • The broken image placeholder appears only on Firefox apparently. Though I'm not sure why plunker behaves like Chrome there. – Skyvory Nov 28 '16 at 08:56

3 Answers3

2

You can conditionally add your img by using *ngIf

<img *ngIf="imageUrl" [src]="imageUrl">
adriancarriger
  • 2,970
  • 3
  • 19
  • 26
2

[src]="imageUrl" is property binding that assigns the value of imageUrl to the src property. This works with all kind of values.

src="{{imageUrl}}" also does property binding but {{}} does string interpolation, this means that imageUrl is stringified before it's assigned to the src property. Don't use this style if you want to pass objects or arrays, or boolean.

When DomSanitizer is used [src]="..." is mandatory because the value no longer is a string, but an object and using {{}} would stringify it in an invalid way.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

The difference is only semantics for your use case.

Using the interpolation option <img src="{{imageUrl}}"> tells angular to put the value of imageUrl into that place holder. In your case, insert it into the value of src property.

Using the template expression option <img [src]="imageUrl"> tells angular to explicitly set the value of the src property to the value of imageUrl.

ppovoski
  • 4,553
  • 5
  • 22
  • 28