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

435
Views
Angular: use una imagen predeterminada si la imagen no existe en el servidor

Tengo un componente que mostrará una imagen de portada. El usuario puede cargar una imagen de portada y el componente mostrará la imagen cargada por el usuario. Si el usuario no carga una imagen, quiero mostrar una imagen predeterminada.

Si no hay una imagen cargada por el usuario, quiero devolver un error y llamar al changeSource (evento), que en teoría debería vincular una nueva URL de imagen al img src. Sin embargo, no estoy definido para event.target.src y veo un espacio en blanco donde debería estar la imagen predeterminada. Funciona bien cuando se muestra la imagen personalizada.

componente.html

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

componente.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

usar directamente (donde defaultImage es una variable en el archivo ts que contiene la ruta de la imagen predeterminada) -

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

tu HTML-

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

Ejemplo de trabajo aquí.

Está pasando un evento desde este código en ts, que obviamente no está definido, y no necesita llamar a esta función desde aquí:

 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

El *ngFor lo estaba descartando. Eliminar esto pareció resolver el problema. No estoy muy seguro de por qué, así que publicaré una edición cuando descubra por qué.

 <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!