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?

1
  • FYI in a template everything is presumed to be part of this so you don't need to prepend your variable name with it. Commented Nov 23, 2017 at 18:41

4 Answers 4

3

It should be just defaultImage

<img src="{{( REST_URL) || defaultImage }}" height="200" />
Sign up to request clarification or add additional context in comments.

3 Comments

what is REST_URL
what happens when you just do thi s <img src="{{ REST_URL + userId }}" height="200" />
3

without this ,a clean way :

<img [src]="REST_URL || defaultImage" height="200" />

3 Comments

@Anarkie where's the rest of the url image .../img.png?
REST_URL is a rest call without /img.png
what's the content of defaultImage and where's the the user image ?
1

showing default image in angular

REST_URL = `user/${this.userId}`;
this.restUrl = REST_URL || defaultImage;
<img [src]="restUrl" height="200" />

1 Comment

type of this.restUrl String?
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.

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.