Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

445
Views
Angular - Use a default image if image does not exist on server

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";
    }

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);
           }, () => {
        }
        );
about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!