Reputation: 847
I'm trying to dynamically create bootstrap badges
based on the value being passed to the div.
HTML
<div
*ngFor="let tag of event.tags">
<span [ngClass]="setTagClass('tag')">
{{tag}}
</span>
</div>
Component Function
public setTagClass(tag){
switch (tag) {
case 'Gaming': {
'badge badge-pill badge-default';
break;
}
case 'Home': {
'badge badge-pill badge-success';
break;
}
case 'Social': {
'badge badge-pill badge-primary';
break;
}
}
}
However it's giving me a _co.setClass is not a function
error spam.
Before this what I attempted to do was daisy chain dynamic versions. IE:
<div
*ngFor="let tag of event.tags">
<span [ngClass]="{'badge badge-pill badge-default': tag == 'Gaming',
'badge badge-pill badge-primary': tag == 'Social'
}">
{{tag}}
</span>
</div>
Ugly - But decent concept... except not -
For some reason the LAST badge to be rendered meeting a requirement looked correct - But the ones before it lose the badge badge-pill
section of their class, but maintained the badge-{color}
section, so it ended up looking like a highlight.
I've seen a lot of different information on ngClass
, class.class
etc and unsure which one is the proper choice to make this work. I feel like this should belong in the controller but I can't seem to make it feedback to the view.
Upvotes: 0
Views: 71
Reputation: 68655
You have passed the tag
as a string to the function - 'tag'
. Remove the ''
from the expression and then return the result from the function.
<div
*ngFor="let tag of event.tags">
<span [ngClass]="setTagClass(tag)">
{{tag}}
</span>
</div>
Function
public setTagClass(tag) {
switch (tag) {
case 'Gaming':
return 'badge badge-pill badge-default';
case 'Home':
return 'badge badge-pill badge-success';
case 'Social':
return 'badge badge-pill badge-primary';
}
}
Upvotes: 2