Search code examples
javascriptangularmarkupng-class

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 }}


Solution

  • 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.