Leon Gaban
Leon Gaban

Reputation: 39018

How to create dynamic class with Angular2's ngClass?

Say in the object models in my cloud Array I have a weight key:

return [
    {
        term: '1994',
        weight: 0
    },
    {
        term: '2017',
        weight: 0
    },
    {
        term: '89th',
        weight: 5
    }

What I want to do is use that weight to create a dynamic class in the markup. Ie: cloud0, cloud9 etc...

How would that be done? Below is the code I tried and error I got.


<span *ngFor="let tag of cloud" [ngClass]="'cloud{{ tag.weight }}'">
    {{ tag.term }}
</span>

<!-- <span class="cloud0">1994</span>
<span class="cloud0">2017</span>
...

enter image description here

Parser Error: Got interpolation ({{}}) where expression was expected at column 6 in ['cloud{{ tag.weight }}'] in EntityComponent@72:56 (": 100%; min-height: 200px;" id="wordcloud"> ][ngClass]="'cloud{{ tag.weight }}'"> {{ tag.term }} "): EntityComponent@72:56 Parser Error: Got interpolation ({{}}) where expression was expected at column 6 in ['cloud{{ tag.weight }}'] in EntityComponent@72:56 ("cloud"> [ERROR ->] {{ tag.term }}

Upvotes: 1

Views: 2518

Answers (2)

El houcine bougarfaoui
El houcine bougarfaoui

Reputation: 37373

<span *ngFor="let tag of cloud" [ngClass]="'cloud '+tag.weight">
    {{ tag.term }}
</span>

Upvotes: 0

dlcardozo
dlcardozo

Reputation: 4013

You can use just html class attribute:

<span *ngFor="let tag of cloud" class="cloud{{ tag.weight }}">
    {{ tag.term }}
</span>

There's no need to use ngClass on this case.

Upvotes: 3

Related Questions