Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Angular to hide a div if an image src resolves with 404 Error

I have this piece of code. It get's the logo of a game from steam

<div class="col-md-3">
        <img src="http://cdn.edgecast.steamstatic.com/steam/apps/{{game.steamID}}/header.jpg" style="width: 100%; height: auto;"/>
    </div>

this is part of a thumbnail div which is tied to a ngFor loop.

now for some context, and my question.

My app uses the steam WebAPI to get a list of all the games a user owns, and stores it in a database.

it then displays the list of these games to the user, with the game logo.

there are some "games" that aren't actually games, dedicated servers mostly. but these non-games don't have any images attached to them. I want to remove these entries from the webpage whenever they crop up. The best way I can think of is to catch any 404 errors and tell the thumbnail to hide itself.

so my question is, is it possible to use ngIf to hide a div if the image url comes back with a 404 error?

EDIT

I'm adding the entire thumbnail's code for anyone that might want to look a the bigger picture.

<div class="thumbnail" style="color: black" *ngFor="let game of games">
<div class="row">
    <div class="col-md-3">
        <img src="http://cdn.edgecast.steamstatic.com/steam/apps/{{game.steamID}}/header.jpg" style="width: 100%; height: auto;"/>
    </div>
    <div class="col-md-9">
        <div class="row">
            <div class="col-md-12">
                <h2>{{game.name}}</h2>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <!--<p>{{countRequests(game.id)}} People want to play<span class="pull-right">Sinse: GET_LAST_REQUEST_DATE</span></p>-->
            </div>
        </div>
    </div>
</div>
</div>
<div class="row">
<div class="col-md-12">
    <div class="centerBlock">
        <div class="btn-group btn-group-lg btn-block">
                        <button *ngIf="page > 1" class="btn btn-primary btn-outline" (click)="previousPage()">Previous</button>
            <button *ngFor="let page of pages" class="btn btn-primary btn-outline"(click)="gotoPage(page)">{{page}}</button>
            <button *ngIf="page < maxPages" class="btn btn-primary btn-outline" (click)="nextPage()">Next</button>
        </div>
    </div>
</div>
</div>
like image 745
Jamie McAllister Avatar asked Dec 19 '22 05:12

Jamie McAllister


1 Answers

Using Angular events you can hide the image itself:

<img #image src="..." (error)="image.hidden = true" [hidden]="image.hidden">

Or any other element:

<div [hidden]="image.hidden"></div>

Or completely remove any div:

<div *ngIf="!image.hidden"></div>
like image 97
Ploppy Avatar answered Dec 20 '22 20:12

Ploppy