2

My <img>:

<img width="90" height="90"  src="{{image}}" />

Default image folder: assets/img/pic_user.png

How can I define a default image that is not defined in the variable: {{image}} ?

viana
  • 495
  • 4
  • 18
  • 42

4 Answers4

8

Use Logical OR operator ||

<img width="90" height="90"  src="{{image||'assets/img/pic_user.png'}}" />
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
7

You can store default image route in variable and then use ternary operator to use it in case image doesn't exist:

defaultImage: string = "assets/img/pic_user.png";

And then in your template:

<img width="90" height="90"  [src]="image ? image : defaultImage" />

Notice that I used property binding instead of interpolation, it is much more elegant in my opinion.

Stefan Svrkota
  • 48,787
  • 9
  • 98
  • 87
1

There is a trick to set default values in JavaScript:

var a = newValue || 0;

Same also works for Angular. In your case:

<img width="90" height="90" src="{{image || 'assets/img/pic_user.png' }}" />
0

Use a fallback image

<img fallback-src="fallbackimg" ng-src="{{image}}"/>

myApp.directive('fallbackSrc', function () {
  var fallbackSrc = {
    link: function postLink(scope, iElement, iAttrs) {
      iElement.bind('error', function() {
        angular.element(this).attr("src", iAttrs.fallbackSrc);
      });
    }
   }
   return fallbackSrc;
});

from: Angular directive for a fallback image

Community
  • 1
  • 1
uzr
  • 1,210
  • 1
  • 13
  • 26