krsna
krsna

Reputation: 4333

How to remove the image element from DOM when 403 error occurs in Angular

Is there a way I can remove the entire image element from DOM when 403 error occurs to that image while fetching it from the API so that the title of the card is expanded to the whole width of the card.

card with no image

This is what I tried so far

HTML

<div *ngFor="let item of items">
  <ion-row>
    <ion-col>
      <div>{{ item.title }}</div>
    </ion-col>
    <ion-col size="4" class="ion-text-center">
      <img src="{{ item.imageurl }}" (error)="handleImageError($event)" />
    </ion-col>
  </ion-row>
</div>

TS

  handleImageError(e) {
    e.target.style.display = 'none';
  }

I have created a working example using StackBlitz. Could anyone please help.

Upvotes: 0

Views: 744

Answers (3)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

Your problem is about your container. U have two columns. Then u will hide column instead of image. U can use ngIf https://stackblitz.com/edit/ionic-a5wy8u

<ion-col *ngIf="!car.isSHOW">
    <ion-card-content>
        <img src="{{car.url}}" (error)="handleImageError(car)">
    </ion-card-content>
</ion-col>

in component change its to true

handleImageError(e) {
   e.isSHOW = true;
  }

Upvotes: 2

Dino
Dino

Reputation: 8292

You are looking for *ngIf on image container, as it removes / adds the element from the DOM. And you will also have to slightly modify the handleImageError.

StackBlitz

<div *ngFor="let item of items">
  <ion-row>
    <ion-col>
      <div>{{ item.title }}</div>
    </ion-col>
    <ion-col *ngIf="!item.hide" size="4" class="ion-text-center">
      <img [src]="item.imageurl" (error)="handleImageError(item)" />
    </ion-col>
  </ion-row>
</div>

And then in the script, in the handleImageError - do this:

items = [
  {imageUrl: '5353ssa.png'},
  {imageUrl: 'https://latam.kaspersky.com/content/es-mx/images/product-icon-KSOS.png'},
  {imageUrl: '5353ssa.png'},
  {imageUrl: '5353ssa.png'},
]

handleImageError(image) {
  image.hide = true;
}

Upvotes: 1

Naveen Motwani - AIS
Naveen Motwani - AIS

Reputation: 619

I would suggest you to use ngIf to hide the complete image, the way I would have address this is

  1. Create a boolean variable at the top of your component.

    let shouldHide = false;

  2. Use this variable and ngIf at your image, you can use this at the container level or the image level itself like.

     <img src="{{ imageurl }}" (error)="handleImageError($event)"  *ngIf="shoudHide"/>
    
    1. Assign true in case of error

      handleImageError(e) { e.target.style.display = 'none'; this.shouldHide = true; }

Hope it helps

Upvotes: 0

Related Questions