如何使用 Angular2 的 ngClass 创建动态 class?
How to create dynamic class with Angular2's ngClass?
在我的云数组中的对象模型中说我有一个权重键:
return [
{
term: '1994',
weight: 0
},
{
term: '2017',
weight: 0
},
{
term: '89th',
weight: 5
}
我想要做的是使用该权重在标记中创建动态 class。即:cloud0
、cloud9
等...
怎么做?下面是我试过的代码和我得到的错误。
<span *ngFor="let tag of cloud" [ngClass]="'cloud{{ tag.weight }}'">
{{ tag.term }}
</span>
<!-- <span class="cloud0">1994</span>
<span class="cloud0">2017</span>
...
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 }}
您可以只使用 html class
属性:
<span *ngFor="let tag of cloud" class="cloud{{ tag.weight }}">
{{ tag.term }}
</span>
在这种情况下不需要使用 ngClass。
<span *ngFor="let tag of cloud" [ngClass]="'cloud '+tag.weight">
{{ tag.term }}
</span>
在我的云数组中的对象模型中说我有一个权重键:
return [
{
term: '1994',
weight: 0
},
{
term: '2017',
weight: 0
},
{
term: '89th',
weight: 5
}
我想要做的是使用该权重在标记中创建动态 class。即:cloud0
、cloud9
等...
怎么做?下面是我试过的代码和我得到的错误。
<span *ngFor="let tag of cloud" [ngClass]="'cloud{{ tag.weight }}'">
{{ tag.term }}
</span>
<!-- <span class="cloud0">1994</span>
<span class="cloud0">2017</span>
...
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 }}
您可以只使用 html class
属性:
<span *ngFor="let tag of cloud" class="cloud{{ tag.weight }}">
{{ tag.term }}
</span>
在这种情况下不需要使用 ngClass。
<span *ngFor="let tag of cloud" [ngClass]="'cloud '+tag.weight">
{{ tag.term }}
</span>