Home > OS >  I want to set a font color according to the value received from the API
I want to set a font color according to the value received from the API

Time:04-01

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>

CodePudding user response:

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')">

CodePudding user response:

You can do one thing store your font color in the public variable.

for example (TS) :

let customColor =xyz; 

or

let customColor;

and let's say you're fetching details from API

const result:any = .get('/apipath'); // API CALL

switch(result.clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor) { 
      case 'Very High': {  
         this.customColor = '#ff5454';
         break; 
      } 
      case 'High': { 
         this.customColor = '#53D8A2';
         break; 
      } 
      default: { // default case is for normal BP
         this.customColor ='#fd9b4b';
         break; 
      } 
   } 
  }

If there is only two case you can use If Else

if(result.clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor === 'High'){
      this.customColor = '#ff5454';
    } else {
      this.customColor ='#fd9b4b';
    }

In HTML file :

[ngStyle]="{'color':customColor }"

CodePudding user response:

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