'I want to set a font color according to the value received from the API
I want to change my font color dynamically.
<div *ngIf="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal'" [ngStyle]="{color:'#ff5454'}" then *ngIf="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='High'" [ngStyle]="{color:'#53D8A2'}" else *ngIf="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal'" [ngStyle]="{color:'#fd9b4b'}" > {{(clientProfileModel.patientHealthScores[0]!=undefined &&
clientProfileModel.patientHealthScores[0].kidney||'')+''}}</div>
Solution 1:[1]
You can do one thing store your font color in the API response by modifying it.
for example (TS) :
and let's say you're fetching details from API
You just have to create one function which returns color based on your parameter like -
this.userService.getUsers().subscribe((res: any) => {
this.users = res;
this.users.map((res) => {
res.customColorForKedney = this.setColor(res.kidneyScoreStatusByColor); // call the function and passed your parameter whatever you have
res.customColorForHeart = this.setColor(res.kidneyScoreStatusByColor);
res.customColorForLiverscore = this.setColor( res.kidneyScoreStatusByColor);
res.customColorForPancreas = this.setColor(res.kidneyScoreStatusByColor);
});
return this.users;
});
}
Function to set color
setColor(key) {
let customColor;
switch (key) {
case 'Very High': {
customColor = '#ff5454';
break;
}
case 'High': {
customColor = '#fd9b4b';
break;
}
default: {
// default case is for normal BP
customColor = '#53D8A2';
break;
}
}
return customColor;
}
In HTML file :
[ngStyle]="{'color':customColor }"
Stackblitz demo: It will surely help you. here
Solution 2:[2]
I think you need to use ternary operator instead of *ngIf. Because in angular you can't use multiple *ngIf in single tag.
<div [style.color]="condition1 ? 'red' : (condition2 ? 'yellow' : 'green')">
<div [style.color]="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='High'? '#53D8A2' : (clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal' ? '#ff5454' : '#fd9b4b')">
Solution 3:[3]
It's probably a good idea to push your logic to the component instead of keeping it in the template.
You can calculate the font color based on your business logic in the component:
fontColor: '#000000'; // A default value
// When your component initializes, decide what the font color should be
ngOnInit() {
if (model.status === 'Normal') {
this.fontColor = '#ff5454';
} else if (model.status === 'High') {
this.fontColor = '#53d8a2';
} // and so on
}
And you can then use fontColor in your template:
<div [ngStyle]="{color: fontColor}">
{{ ... }}
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Ravi Mashru |
