1
votes

In our component, we retrieve through http a JSON containing various styling for our element:

{
  id: 1,
  style: "color: red; background-color: white;",
  class: "fa-times",
},
{
  id: 2,
  style: "",
  class: "fa-check active",
}

I can't really change the JSON retrieves as it's from an external source.

Then I want to apply that style in a ngFor loop:

<li *ngFor="let element of elements">
  <i class="fa" style=""></i> {{element .id}}
</li>

But now I want to add the classes and styles defined as strings in JSON into my element.

Classes

I tried something like [class] = "fa {{element.class}}" but it triggers an error:

Uncaught (in promise): Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 3 in [fa {{element.class}}]

I managed to get the class part of my request working by using ngClass as suggered in some website and an answer here:

class="fa" [ngClass]="possibility.class"

It works. But I still struggle to apply requested styles.

Styles

I tried several methods:

[style]="possibility.style"

It then triggers the xss protection of Angular2:

WARNING: sanitizing unsafe style value color: green (see http://g.co/ng/security#xss).

WARNING: sanitizing unsafe style value color: green (see http://g.co/ng/security#xss).

WARNING: sanitizing unsafe style value color: red (see http://g.co/ng/security#xss).

WARNING: sanitizing unsafe style value color: red (see http://g.co/ng/security#xss).

I also tried style="{{possibility.style}}" and of course it triggers the same XSS protection guard.

I tried the ngStyle method:

[ngStyle]="possibility.style"

But it seems not to be able to parse the style as it is parsed from JSON (e.g: string color: green; background-color: white;. Even a single style like color: green; breaks the script):

Error in ./ProjectComponent class ProjectComponent - inline template:15:14 caused by: Cannot find a differ supporting object 'color: green'

ORIGINAL EXCEPTION: Cannot find a differ supporting object 'color: green'

2
I have lots of ways of doing this, but SO isn't a "do it for me" site. What approaches have you tried so far? What tools did you use? Have you read the docs for those tools? In what way(s) did things not work as expected? Do you have snippets of specific code that did not work?Peter Rowell
Hi Peter, I updated the page to list all my attemptsBlackHoleGalaxy

2 Answers

2
votes

You can use ngClass:

<li *ngFor="let element of elements">
  <i class="fa" [ngClass]="element.class"></i> {{element.id}}
</li>
1
votes

Have the class attribute bind to a property of your component:

<i [class]="myProperyInMyComponent"></i> {{element .id}}

in your component:

myPropertyInMyComponent: string

once you get back the result from your http:

this.myPropertyInMyComponent = ....

see template syntax