user6039980
user6039980

Reputation: 3506

ngStyle: Error saying "Missing expected }"

I'm getting the following error from chrome console, when interpreting

<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/HomeComponent.html@31:29 ("="width: 100%; height: 100%;">

What's supposed to cause the error?

Upvotes: 4

Views: 4549

Answers (2)

Bal Krishna Jha
Bal Krishna Jha

Reputation: 7206

In newer version you can also use unit.

The key is a style name, with an optional . suffix (such as 'top.px', 'font-style.em').

Like

[ngStyle]="{'width.px':200, 'height.px':200}"

Upvotes: 1

Soviut
Soviut

Reputation: 91525

Unlike the style attribute which takes CSS styles, ngStyle takes a javascript object (represented in a string). That's why you have to wrap 100% in quotes '100%', as well as other attributes like background-size because % and - characters are illegal in javascript attribute names/values.

CSS

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

Object

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

Because of this, you need to replace the ; with ,.

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

NOTE: ngStyle is supposed to be used if you have dynamic values you're trying to set. It allows you to pass variables into the styles as well as toggle specific styles using booleans. If you're just trying to set inline styles, you should use the normal style attribute.

Upvotes: 9

Related Questions