我想動態更改我的字體顏色。
<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>
uj5u.com熱心網友回復:
我認為您需要使用三元運算子而不是 *ngIf。因為在角度中,您不能在單個標簽中使用多個 *ngIf。
<div [style.color]="condition1 ? 'red' : (condition2 ? 'yellow' : 'green')">
<div [style.color]="clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='High'? '#53D8A2' : (clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor==='Normal' ? '#ff5454' : '#fd9b4b')">
uj5u.com熱心網友回復:
您可以做一件事將字體顏色存盤在公共變數中。
例如(TS):
let customColor =xyz;
要么
let customColor;
假設您正在從 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 Else
if(result.clientProfileModel.patientHealthScore[0].kidneyScoreStatusByColor === 'High'){
this.customColor = '#ff5454';
} else {
this.customColor ='#fd9b4b';
}
在 HTML 檔案中 :
[ngStyle]="{'color':customColor }"
uj5u.com熱心網友回復:
將邏輯推送到組件而不是將其保留在模板中可能是個好主意。
您可以根據組件中的業務邏輯計算字體顏色:
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
}
然后您可以fontColor在模板中使用:
<div [ngStyle]="{color: fontColor}">
{{ ... }}
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/455186.html
