2016-11-09 72 views
6

我試圖使用NgStyle指令與對象變量,像這樣:如何將Object傳遞給Angular 2中的NgStyle指令?

@Component({ 
     template: ` 
      <div [ngStyle]="object"> 
       some test text 
      </div>` 
    }) 

export class example { 
    private object: string = "{background-color: 'white'}"; 
} 

我也試圖與object = "background-color: 'red'"[ngStyle]="{object}",但似乎這是行不通的。我收到消息錯誤:

Error: Uncaught (in promise): Error caused by: Cannot find a differ supporting object '{color: 'white'}'(…)consoleError @ VM1051 [email protected]?main=browser:346_loop_1 @ VM1051 [email protected]?main=browser:371drainMicroTaskQueue @ VM1051 [email protected]?main=browser:375ZoneTask.invoke @ VM1051 [email protected]?main=browser:297

我在做什麼錯?

+1

「作爲一個對象,像這樣」但你傳遞一個字符串。 – msanford

回答

11

沒有傳遞到string[ngStyle],傳遞一個Object,它會工作:

private object: Object = { 'background-color': 'red'}; 
+0

模板可綁定的屬性應該是公共的 –

2

我有ngStyle類似的問題,並固定它,如下所示:

[ngStyle]="{'top.px':dtPickerTop, 'left.px':dtPickerLeft}" 

dtPickerTop & dtPickerLeft基於單擊事件在我的組件中設置。

添加.px使其工作,而沒有它,它似乎並沒有。

相關問題