Search code examples
angulartypescriptpokeapi

Unable to display animated sprites from PokeAPI in Angular Project


I am developing a Pokedex project using Angular.

I am fetching the PokeAPI successfully and I can display the regular sprites by writing:

<img [src]="pokemon[0].sprites.front_default" [alt]="pokemon[0].name" >

but when I try to display an animated gif in a different directory by writing:

[src]="pokemon[0].sprites.versions.generation-v.black-white.animated.front_default"

it throws me two errors stating:

Property 'v' does not exist on type 'DetailsComponent'.

Property 'white' does not exist on type 'DetailsComponent'.

This is happening because I have to parse a text containing a hyphen and Angular reads it as something else

What would be the correct way of parsing the source of the image without having issues?


Solution

  • I suggest you obtain the text for the image in your typescript file, save it in the variable, pokemonImage, and use the variable as the value for the [src] property.
    On your HTML page have something like this: <img id="imageOfPokemon" alt="{{pokemonName}}" src="{{pokemonImage}}" width="250" height="250"/>.
    In your typescript file, create the property pokemonImage: string = '', and save the following as the value: this.pokemonImage = pokemon['sprites']['versions']['generation-v']['black-white']['animated'].front_default;