Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

441
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda