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}} ?

4 Answers 4

8

Use Logical OR operator ||

<img width="90" height="90"  src="{{image||'assets/img/pic_user.png'}}" />
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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' }}" />

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.