2

This is what I have in my html file:

<img src="{{( REST_URL + userId) || this.defaultImage }}" height="200" />

REST_URL is user/ (on browser call http://localhost:8080/user/123456 shows user image)

in my component.ts file variables are defined as below:

readonly REST_URL = 'user/';
userId: number;

Not all users have an image and I expect default image to be shown when the user doesn't have an image but it doesn't work... any ideas?

Anarkie
  • 657
  • 3
  • 19
  • 46
  • FYI in a template everything is presumed to be part of `this` so you don't need to prepend your variable name with it. – msanford Nov 23 '17 at 18:41

4 Answers4

3

It should be just defaultImage

<img src="{{( REST_URL) || defaultImage }}" height="200" />
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
3

without this ,a clean way :

<img [src]="REST_URL || defaultImage" height="200" />
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
1

showing default image in angular

REST_URL = `user/${this.userId}`;
this.restUrl = REST_URL || defaultImage;
<img [src]="restUrl" height="200" />
msanford
  • 11,803
  • 11
  • 66
  • 93
0

As mentioned in other answers, you don't need to specify this in your template when referring to the component class members. And there is another problem in your code...

You assume that, if the user image doesn't exist, the default image will be used as a result of the following expression:

(REST_URL + userId) || defaultImage

But that expression will never evaluate to defaultImage because (REST_URL + userId) is never falsy. Even if the image doesn't exist, its URL is not null, undefined or empty. Therefore, the user image URL is always used.


Solution 1

If you have a flag that indicates if the user image exists or not, you can use code like this:

<img [src]="imageExists ? REST_URL + userId : defaultImage" height="200" />

Solution 2

Another solution is to handle the error event and to change the URL to the default image if the user image cannot be loaded:

<img [src]="imageUrl" height="200" (error)="onError()" />
private defaultImage = "http://www.yourWebSite.com/yourDefaultImage.jpg";

public imageUrl = REST_URL + this.userId;

public onError(): void {
    this.imageUrl = this.defaultImage;
}

You can try the code in this plunker. After running it and seeing the "user image", you can make userImage incorrect in the code and see that the "default image" is displayed.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146