Angular 5 - 在 HTML CSS 中使用來自視圖模型的變數
我在我的視圖模型中有一個變量,其設置器和取值器叫做:orderStatusColor。
這是一個字串如下:"color: red" 或 "color: green"。
我如何在我的 HTML 中使用這個作為樣式?我試過使用 ngStyle,但我收到一個錯誤說
"DevicesStatusComponent.html:12 錯誤 Error: 無法找到支援對象 'color: red' 的差異器"
控制器.ts
private orderStatusColorCode(code: string){
const codeRed = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
if(codeRed.some(s => s.includes(code))){
this.orderStatusColor = "color: red";
}
return this.orderStatusColor;
}
orderViewModel.devices =
new DevicesStatusViewModel(
this.orderStatusColor
);
view-model.ts
interface DevicesStatusViewModelI {
orderStatusColor: string;
}
export class DevicesStatusViewModel implements DevicesStatusViewModelI {
private _orderStatusColor = '';
get orderStatusColor(): string { return this._orderStatusColor; }
set orderStatusColor(orderStatusColor: string) {
this._orderStatusColor = (orderStatusColor != null) ? orderStatusColor : "";
}
constructor(orderStatusColor?: string) {
this.orderStatusColor = orderStatusColor;
}
}
HTML
<ng-container>
<p ngStyle="{{devicesStatusViewModel.orderStatusColor}}">Test</p>
</ng-container>
答案#1
更改以下內容
if(codeRed.some(s => s.includes(code))){
this.orderStatusColor = '{"color": "red"}';
}
像下面這樣在組件中將 JSON 字串解析為 JSON 對象(因為 ngStyle 期望的是一個對象)
this.orderStatusColor = JSON.parse('{"color": "red"}');
現在你可以在模板 HTML 中使用它,例如
<div [ngStyle]="orderStatusColor">
答案#2
看起來,你在變數 devicesStatusViewModel.orderStatusColor 中傳遞了一個字串,但它應該是一個物件。就像下面這樣
component.ts
public style = {color:'blue'};
component.html
<h1 [ngStyle]="style">This is header in blue</h1>
