angularangular-ng-class

How to use a function and expression in a ngClass using Angular?


I'm currently trying to show a list of Pokemons that have a different background color depending on their type. I would like to implement a feature where the border of the selected pokemon also shows with a gold border color. If I use them one at a time they work just fine but i'm having trouble using them together.

My html is the following:

<h1>Pokédex</h1>
<p [hidden]="!selectedPokemon">Geselecteerde pokemon: {{selectedPokemon}}</p>
<div class="wrapper">
  <app-pokemon (selectedPokemon)="highlightPokemon($event)"
               *ngFor="let item of pokemons"
               [pokemon]="item"
               [ngClass]="{getType(item.type), item.name === selectedPokemon ? 'select' : ''}">
  </app-pokemon>
</div>

My getType function is the following:

getType(pokemonType: string): string {
    pokemonType = pokemonType.toLowerCase();
    switch(pokemonType) {
      case 'grass': {
        return 'grass'
      }
      case 'fire': {
        return 'fire'
      }
      case 'water': {
        return 'water'
      }
      default: {
        return 'grass'
      }
    }
  }

The error my IDE is complaining about:

enter image description here

I also tried the following:

[ngClass]="getType(item.type), item.name === selectedPokemon ? 'select' : ''">

enter image description here

Thanks a lot for helping!


Solution

  • You can using [className]="getType(item.type)" and [class.select]="item.name === selectedPokemon"