Home > Net >  Angular - Use a default image if image does not exist on server
Angular - Use a default image if image does not exist on server

Time:12-02

I have a component that will display a cover image. The user can upload a cover image and the component will display the user uploaded image. If the user doesn't upload an image, then I want to display a default image.

If there is no user uploaded image I want to return an error and call the changeSource(event), which should in theory bind a new image url to the img src. However I'm getting undefined for the event.target.src and I'm seeing a blank space where the default image should be. It works fine when displaying the custom image.

component.html

<div *ngFor="let coverPhoto of coverPhotos">
    <img src="{{coverPhoto}}"
         (error) ="changeSource($event)" />
</div>

component.ts

this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
            this.coverPhotos = result;
        }, error => {
                this.errors = error;
                this.changeSource(event);
           }, () => {
        }
        );

changeSource(event) {      
        event.target.src = "https://imageurl";
    }

CodePudding user response:

directly use (where defaultImage is a variable in ts file which holds the default image path) -

(error)="$event.target.src = defaultImage"

your HTML -

<div *ngFor="let coverPhoto of coverPhotos">
  <img src="{{ coverPhoto }}" (error)="$event.target.src = defaultImage" />
</div>

Working example here.

You are passing event from this code in ts, which is obviously undefined, and you don't need to call this function from here -

this.myService.getPhotos(ImageType.Cover, this.id).subscribe(result => {
            this.coverPhotos = result;
        }, error => {
                this.errors = error;
                this.changeSource(event);
           }, () => {
        }
        );

CodePudding user response:

The *ngFor was throwing it off. Removing this seemed to solve the problem. Not quite sure why so will post an edit when I discover why.

<div>
    <img src="{{coverPhotos}}"
         (error)="$event.target.src = defaultImage" />
</div>

  • Related