2017-08-29 31 views
1

我解釋ngStyle:說「失蹤預期}」錯誤

<div [ngStyle]="{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat': 'no-repeat'; 'border-radius': '0px';}"></div> 

Uncaught Error: Template parse errors: Parser Error: Missing expected } at column 17 in [{'width': '100%'; 'height': '100%'; 'background-size': 'cover'; 'background-repeat': 'no-repeat'; 'border-radius': '0px';}] in ng:///AppModule/[email protected]:29 ("="width: 100%; height: 100%;">

什麼是應該引起錯誤,當我得到的鉻控制檯,下面的錯誤?

+1

我猜'''在對象字面值內應該是',' –

+1

@GünterZöchbauer這顯然是我必須做的。謝謝。 – Kais

回答

3

與採用CSS樣式的style屬性不同,ngStyle需要JavaScript對象(以字符串表示)。這就是爲什麼您必須將100%換成引號'100%'以及其他屬性,如background-size,因爲%-字符在JavaScript屬性名稱/值中是非法的。

CSS

blah { 
    attribute: value; 
    attribute-dash: value; 
} 

對象

{ 
    attribute: value, 
    'attribute-dash': value 
} 

正因爲如此,你需要,更換;

<div [ngStyle]="{'width': '100%', 'height': '100%', 'background-size': 'cover', 'background-repeat': 'no-repeat', 'border-radius': '0px'}"></div> 

注:ngStyle應該是,如果你有你想設置的動態值使用。它允許您將變量傳遞到樣式中,並使用布爾值切換特定樣式。如果您只是試圖設置內聯樣式,則應使用正常的style屬性。

+0

感謝您的解釋。現在我明白它是如何工作的。 – Kais