Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

436
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda