[英]How to apply multiple object property to ngStyle
我的 HTML 中有一個元素,如下所示: <span [ngStyle]="{'background': getColor(selectedOption.type)}">BLAH</span>
我的 TS 文件中有這樣的條件:
public getColor(type: string){
switch (type) {
case 'General':
return {background: '#ffe5d7', color: '#e7560a' };
case 'Interview':
return { background: '#ffe5d7', color: '#e7560a' };
//more code
基本上,如果用戶選擇“常規”,我希望從 function 返回正確的背景和字體顏色,並使用 ngStyle 應用於元素。 但這不能正常工作。 我究竟做錯了什么?
嘗試這個:
<span [ngStyle]="getColor(selectedOption?.type)">BLAH</span>
public getColor(type: string | undefined){
if (type) {
switch (type) {
case 'General':
return {background: '#ffe5d7', color: '#e7560a' };
case 'Interview':
return { background: '#ffe5d7', color: '#e7560a' };
//more code
case default:
return {};
}
return {};
}
編輯:我剛剛讀過@Onur Baştürk 在我面前回答過。 他是對的,您正在復制背景屬性,一個在 HTML ([ngStyle]="{'background':...) 中,另一個在您的 ts 代碼中:
return {background: '#ffe5d7', color: '#e7560a' ....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.